CodeGym /Courses /JAVA 25 SELF /Searching and sorting elements in Java collections

Searching and sorting elements in Java collections

JAVA 25 SELF
Level 29, Lesson 4
Available

1. Searching for elements in collections

Searching using standard methods

When we have a list, for example, of names:

List<String> names = List.of("Anna", "Boris", "Viktoriya", "Anna", "Dmitriy");

Java provides several convenient search methods:

  • contains(Object o) — checks whether the collection contains the element.
  • indexOf(Object o) — returns the first index of the element (or -1 if not found).
  • lastIndexOf(Object o) — returns the last index of the element (or -1).

Examples:

System.out.println(names.contains("Anna"));      // true
System.out.println(names.indexOf("Anna"));       // 0
System.out.println(names.lastIndexOf("Anna"));   // 3
System.out.println(names.contains("Sergey"));    // false

Fact: For collections of type Set, there are no indexOf and lastIndexOf methods — a Set has no indices at all, only unique values.

Conditional search

Sometimes you need to find not a specific value, but an element that matches a condition. For example, find the first name longer than 6 characters. A plain for loop works great: as soon as you find a matching element — use break.

List<String> names = List.of("Anna", "Boris", "Viktoriya", "Anna", "Dmitriy");

String found = null;
for (String name : names) {
    if (name.length() > 6) {
        found = name;
        break; // Found the first match; we can exit the loop
    }
}
System.out.println(found); // Viktoriya

Finding maximum and minimum

For collections with comparable elements (for example, numbers) you can quickly find the maximum and minimum using the Collections class.

List<Integer> numbers = List.of(10, 5, 20, 7, 20, 3);

int max = Collections.max(numbers); // 20
int min = Collections.min(numbers); // 3

System.out.println("Maximum: " + max);
System.out.println("Minimum: " + min);

Important: Elements must be comparable (implement Comparable), otherwise you need to pass a comparator.

2. Sorting collections

Default list sorting

You can only sort mutable lists (for example, ArrayList, LinkedList). Collections like Set and Map do not support sorting directly.

By default, sorting goes by “natural order”: for numbers — ascending; for strings — alphabetical.

List<Integer> numbers = new ArrayList<>(List.of(5, 1, 7, 3));
Collections.sort(numbers);
System.out.println(numbers); // [1, 3, 5, 7]

The same can be done via the list’s sort method:

List<Integer> numbers = new ArrayList<>(List.of(5, 1, 7, 3));
numbers.sort(null); // null means: use natural order
System.out.println(numbers); // [1, 3, 5, 7]

Sorting with a comparator

If you need a custom rule — for example, sort strings by length:

List<String> words = new ArrayList<>(List.of("cat", "elephant", "fly", "rhinoceros"));

words.sort(Comparator.comparingInt(String::length));
System.out.println(words); // [cat, fly, elephant, rhinoceros]

In reverse order:

words.sort(Comparator.comparingInt(String::length).reversed());
System.out.println(words); // [rhinoceros, fly, elephant, cat]

Old style via Collections.sort:

Collections.sort(words, Comparator.comparingInt(String::length));

3. Sorting specifics for different collections

Sorting only modifies a list

Sorting methods (sort, Collections.sort) work only with collections that maintain element order (for example, List). Such methods are not provided for Set and Map.

Attempting to sort a Set:

Set<Integer> mySet = new HashSet<>(List.of(3, 1, 2));
Collections.sort(mySet); // Compilation error: sort expects a List!

If you need a sorted list from a Set:

List<Integer> sortedFromSet = new ArrayList<>(mySet);
Collections.sort(sortedFromSet);
System.out.println(sortedFromSet); // [1, 2, 3]

Sorting a Map: by keys and by values

You can’t sort a Map directly, but you can:

  • Get a list of key–value pairs
  • Sort it as needed
  • If necessary, build a new Map

Example: sorting by values

Map<String, Integer> scores = Map.of(
    "Anna", 15,
    "Boris", 20,
    "Vika", 12
);

List<Map.Entry<String, Integer>> entries = new ArrayList<>(scores.entrySet());
entries.sort(Map.Entry.comparingByValue());

for (Map.Entry<String, Integer> entry : entries) {
    System.out.println(entry.getKey() + ": " + entry.getValue());
}
// Vika: 12
// Anna: 15
// Boris: 20

Sorting objects by a field

Suppose we have a user class:

class User {
    String name;
    int age;
    User(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return name + " (" + age + ")";
    }
}

And a list of users:

List<User> users = new ArrayList<>(List.of(
    new User("Anna", 22),
    new User("Boris", 18),
    new User("Vika", 25)
));

Sort by age:

users.sort(Comparator.comparingInt(u -> u.age));
System.out.println(users); // [Boris (18), Anna (22), Vika (25)]

In reverse order:

users.sort(Comparator.comparingInt((User u) -> u.age).reversed());
System.out.println(users); // [Vika (25), Anna (22), Boris (18)]

4. Common mistakes when searching and sorting collections

Mistake No. 1: Sorting an immutable list. Lists created via List.of(...) cannot be modified — calling sort will result in UnsupportedOperationException.

List<Integer> immutable = List.of(3, 1, 2);
immutable.sort(null); // Will throw an exception!

Mistake No. 2: Sorting a Set or Map directly. Sorting methods don’t work with Set and Map. If you need sorting, first convert the data to a list.

Mistake No. 3: Incorrect object comparison. Don’t subtract integers “as-is” when comparing — overflows are possible. Instead of u1.age - u2.age, use Integer.compare or Comparator.comparingInt.

// users.sort((u1, u2) -> u1.age - u2.age); // Works, but unsafe due to potential overflow!

Mistake No. 4: Using contains for complex searches. The contains method checks only for exact matches (via equals). If you need to search by a substring or by an object’s field, use a loop with a condition or comparators/streams.

1
Task
JAVA 25 SELF, level 29, lesson 4
Locked
Tracking an animal's appearances in the forest 🌲🐾
Tracking an animal's appearances in the forest 🌲🐾
1
Task
JAVA 25 SELF, level 29, lesson 4
Locked
Match Results Analysis in the Game League 🎮📊
Match Results Analysis in the Game League 🎮📊
1
Survey/quiz
Comparators and object comparison, level 29, lesson 4
Unavailable
Comparators and object comparison
Comparators and object comparison
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION