After knowing the fundamentals of interface Comparator, let us make a small example. ArrayList elements are printed in reverse order using Comparator. Example code on Comparator Example Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.util.*; public class ComparatorExample { public static void main(String args[]) { ArrayList stones = new ArrayList(); stones.add("pearl"); stones.add("diamond"); stones.add("ruby"); stones.add("emerald"); stones.add("topaz"); Comparator comp1 = Collections.reverseOrder(); System.out.println("Default order of stones: " + stones); Collections.sort(stones, comp1); System.out.println("Stones in reverse order: " + stones); } } |
Output screenshot on Comparator Example Java ArrayList stones = new ArrayList(); stones.add(“pearl”); An ArrayList object stones is created and added a…