Skip to content

Commit

Permalink
feat: Add Comparator Example
Browse files Browse the repository at this point in the history
  • Loading branch information
VishwajeetVT committed Dec 13, 2024
1 parent ceab87d commit 386b1f6
Showing 1 changed file with 27 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -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<ComparableDemo> 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<ComparableDemo>() {
// @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);
}
}

0 comments on commit 386b1f6

Please sign in to comment.