DEV Community

DevCorner2
DevCorner2

Posted on

Comparator Java

Here's a well-structured and organized version of your original content on sorting in Java using Comparator for arrays, lists, maps, sets, queues, and custom objects:


โœ… Java Sorting with Comparator โ€“ A Complete Guide


๐Ÿ“Œ 1. Sorting Arrays

๐Ÿ”น1.1 Sort 2D int Array by First Element, Then Second

int[][] arr = { {1, 2}, {4, 5}, {1, 1}, {23, 2} };

Arrays.sort(arr, (a, b) -> {
    if (a[0] != b[0]) return Integer.compare(a[0], b[0]);
    return Integer.compare(a[1], b[1]);
});

// Print result
for (int[] pair : arr) {
    System.out.println(Arrays.toString(pair));
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”น1.2 Sort Integer Array in Descending Order

Integer[] arr = {4, 2, 1, 45, 7, 23, 45};

// Method 1: Custom Comparator
Arrays.sort(arr, (a, b) -> b - a);

// Method 2: Using -a in Comparator
Arrays.sort(arr, Comparator.comparingInt(a -> -a));

// Print result
System.out.println(Arrays.toString(arr));
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“Œ 2. Sorting String Arrays

๐Ÿ”น2.1 Lexicographically (Aโ€“Z)

String[] names = {"Charlie", "Alice", "Bob"};
Arrays.sort(names);
System.out.println(Arrays.toString(names));
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”น2.2 Reverse Order (Zโ€“A)

Arrays.sort(names, Comparator.reverseOrder());
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”น2.3 By Length

String[] words = {"banana", "fig", "apple", "kiwi"};
Arrays.sort(words, Comparator.comparingInt(String::length));
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“Œ 3. Sorting User-Defined Objects

๐Ÿ‘ค User Class

public class User {
    String name;
    int age;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return name + " (" + age + ")";
    }
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”น3.1 Sort by Name

Arrays.sort(users, Comparator.comparing(user -> user.name));
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”น3.2 Sort by Age (Ascending)

Arrays.sort(users, Comparator.comparingInt(user -> user.age));
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”น3.3 Sort by Age (Descending)

Arrays.sort(users, Comparator.comparingInt((User u) -> u.age).reversed());
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”น3.4 Sort by Name, Then Age

Arrays.sort(users, Comparator
    .comparing((User u) -> u.name)
    .thenComparingInt(u -> u.age));
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“Œ 4. Sorting Java Collections

๐Ÿ”ธ4.1 List

โ–ถ๏ธ List of Strings

List<String> names = Arrays.asList("Charlie", "Alice", "Bob");
Collections.sort(names);  // Or names.sort(...)
Enter fullscreen mode Exit fullscreen mode

โ–ถ๏ธ List of Custom Objects

List<User> users = Arrays.asList(
    new User("Bob", 30),
    new User("Alice", 25)
);

users.sort(Comparator.comparingInt(u -> u.age));
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”ธ4.2 Map<K, V>

Maps canโ€™t be sorted directly but can be converted to a stream and sorted.

โ–ถ๏ธ Sort by Key

Map<String, Integer> map = new HashMap<>();
// put entries...

Map<String, Integer> sortedByKey = map.entrySet().stream()
    .sorted(Map.Entry.comparingByKey())
    .collect(Collectors.toMap(
        Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new
    ));
Enter fullscreen mode Exit fullscreen mode

โ–ถ๏ธ Sort by Value

Map<String, Integer> sortedByValue = map.entrySet().stream()
    .sorted(Map.Entry.comparingByValue())
    .collect(Collectors.toMap(
        Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new
    ));
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”ธ4.3 Set

โ–ถ๏ธ Use TreeSet

Set<String> sortedSet = new TreeSet<>();
Enter fullscreen mode Exit fullscreen mode

โ–ถ๏ธ Sort HashSet via List

Set<String> hashSet = new HashSet<>(Arrays.asList("Charlie", "Alice", "Bob"));
List<String> sortedList = new ArrayList<>(hashSet);
Collections.sort(sortedList);
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”ธ4.4 Queue

โ–ถ๏ธ Convert Queue to List

Queue<String> queue = new LinkedList<>();
List<String> list = new ArrayList<>(queue);
Collections.sort(list);
Enter fullscreen mode Exit fullscreen mode

โ–ถ๏ธ Use PriorityQueue with Comparator

Queue<User> pq = new PriorityQueue<>(Comparator.comparingInt(u -> u.age));
pq.add(new User("Charlie", 30));
pq.add(new User("Alice", 25));

while (!pq.isEmpty()) {
    System.out.println(pq.poll());
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”ธ4.5 Deque

โ–ถ๏ธ Sort by Converting to List

Deque<String> deque = new ArrayDeque<>(Arrays.asList("Charlie", "Alice", "Bob"));
List<String> sorted = new ArrayList<>(deque);
Collections.sort(sorted);
deque.clear();
deque.addAll(sorted);
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“Œ 5. Custom Comparator Class

public class UserNameAgeComparator implements Comparator<User> {
    public int compare(User u1, User u2) {
        int nameCompare = u1.name.compareTo(u2.name);
        return nameCompare != 0 ? nameCompare : Integer.compare(u1.age, u2.age);
    }
}

// Usage:
Arrays.sort(users, new UserNameAgeComparator());
Enter fullscreen mode Exit fullscreen mode

๐Ÿ Summary

Type Approach Tools Used
Primitive Arrays.sort Built-in
Objects Comparator + Lambda Comparator.comparing()
Collections Collections.sort / stream LinkedHashMap, TreeSet, etc
Queues PriorityQueue or convert Comparator

Top comments (0)