Comparator

Comparator Example Java

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 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 …

Comparator Example Java Read More »

interface Comparator

Comparator interface is from java.util package like other data structures. Some data structures TreeSet and TreeMap sort the elements in natural (ascending) order by default. The Comparator object is capable to change this order, the way customization requires. Programmer can get a precise control over ordering. In Java, we come across a list of objects …

interface Comparator Read More »

Comparable vs Comparator

At the outset, both are used for ordering the elements of a data structure in the way the programmer desires. Just they differ in their methods of implementation and usage with objects in comparison. These two interfaces are best suitable for ordering the objects depending on their fields. For example, student objects can be ordered …

Comparable vs Comparator Read More »