javabeginner

Java List Operations and Utilities

Essential List operations: create, sort, search, transform, partition, and immutable list patterns.

java
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class ListOps {
    public static void main(String[] args) {
        // Create lists
        List<String> immutable = List.of("a", "b", "c"); // unmodifiable
        List<String> mutable = new ArrayList<>(List.of("a", "b", "c"));
        List<Integer> range = IntStream.rangeClosed(1, 10).boxed().toList();

        // Sort
        mutable.sort(Comparator.reverseOrder());
        mutable.sort(Comparator.comparing(String::length).thenComparing(Comparator.naturalOrder()));

        // Binary search (list must be sorted)
        Collections.sort(mutable);
        int idx = Collections.binarySearch(mutable, "b");

        // Partition into chunks
        List<Integer> numbers = IntStream.rangeClosed(1, 25).boxed().toList();
        int chunkSize = 10;
        List<List<Integer>> chunks = IntStream.range(0, (numbers.size() + chunkSize - 1) / chunkSize)
            .mapToObj(i -> numbers.subList(
                i * chunkSize,
                Math.min((i + 1) * chunkSize, numbers.size())))
            .toList();
        System.out.println(chunks); // [[1..10], [11..20], [21..25]]

        // Frequency map
        List<String> words = List.of("a", "b", "a", "c", "b", "a");
        Map<String, Long> freq = words.stream()
            .collect(Collectors.groupingBy(w -> w, Collectors.counting()));

        // Zip two lists
        List<String> names = List.of("Alice", "Bob");
        List<Integer> ages = List.of(30, 25);
        List<String> zipped = IntStream.range(0, Math.min(names.size(), ages.size()))
            .mapToObj(i -> names.get(i) + ": " + ages.get(i))
            .toList();

        // Remove duplicates preserving order
        List<Integer> withDupes = List.of(3, 1, 2, 1, 3, 4);
        List<Integer> unique = withDupes.stream().distinct().toList();

        // Flatten nested lists
        List<List<Integer>> nested = List.of(List.of(1, 2), List.of(3, 4));
        List<Integer> flat = nested.stream().flatMap(Collection::stream).toList();
    }
}

Use Cases

  • Common list manipulation patterns
  • Batch processing with list chunking
  • Data deduplication and frequency counting

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.