Custom sorting using a comparator

  • Eclipse: Oxygen
  • Java: 1.8

Custom sorting using a comparator is used to order the user-defined methods. In addition to using the generics, various data types which could integers, Strings etc. and Moreover Key value pair which is shown as below.

In the following example, a Data class is created which accepts data as key-value pair.

A set is created which will accept data of custom class type in key-value format.

To sort the data of this custom type a comparator interface is implemented with custom logic. It will sort the data on key order.

Output

Data [key=1, value=Chaand]

Data [key=2, value=Arnold J]

Data [key=5, value=Ed]

Data [key=9, value=John]

In following example, a custom logic is defined in comparator to sort element according to length of name string.

Output

Data [key=5, value=Ed]

Data [key=5, value=Mia]

Data [key=9, value=John]

Data [key=1, value=Chaand]

Data [key=2, value=Arnold J]

Contributed by Poonam Tomar


Full stack Java Developer

   Buy me a coffee!

 

PayTM QR (INDIA)

Download file

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu