From 386b1f6d4e2eeb1a490f10873242d5306828637a Mon Sep 17 00:00:00 2001 From: VishwajeetK Date: Fri, 13 Dec 2024 12:51:14 +0530 Subject: [PATCH] feat: Add Comparator Example --- .../dsa/collections/ComparatorExample.java | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 JavaDsaWithTest/src/main/java/org/practice/dsa/collections/ComparatorExample.java 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); + } +}