diff --git a/JavaDsaWithTest/src/main/java/org/practice/dsa/collections/ComparatorExample.java b/JavaDsaWithTest/src/main/java/org/practice/dsa/collections/ComparatorExample.java new file mode 100644 index 0000000..69d172d --- /dev/null +++ b/JavaDsaWithTest/src/main/java/org/practice/dsa/collections/ComparatorExample.java @@ -0,0 +1,27 @@ +package org.practice.dsa.collections; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +public class ComparatorExample { + public static void main(String[] args) { + List demo = new ArrayList<>(); + demo.add(new ComparableDemo(3, "V")); + demo.add(new ComparableDemo(1, "B")); + demo.add(new ComparableDemo(2, "X")); + +// Collections.sort(demo, new Comparator() { +// @Override +// public int compare(ComparableDemo o1, ComparableDemo o2) { +// return o1.getName().compareTo(o2.getName()); +// } +// }); + // short form + Collections.sort(demo, Comparator.comparing(ComparableDemo::getName)); + + System.out.println("Sort by names:"); + demo.forEach(System.out::println); + } +}