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)