Flat Preloader Icon

Java Collectors

In Java, the java.util.stream.Collectors class is part of the Stream API introduced in Java 8. It provides a wide range of built-in reduction operations that can be used to collect elements from a stream into various data structures, apply transformations, and perform aggregations. These operations are essential for working with streams in a more structured and functional way. Here are some of the common methods and use cases for the Collectors class:
  • toList():
  • Collects elements into a List:
    					List<String> names = people.stream()
  • toSet():
  • Collects elements into a Set, removing duplicates:
    					Set<Integer> uniqueNumbers = numbers.stream()
  • toCollection():
  • Collects elements into a specified collection:
    					LinkedList<String> linkedList = 
  • toMap():
  • Collects elements into a Map, using key and value mappers:
    					Map<Integer, String> idToName = people.stream()
    (Person::getId, Person::getName));
  • joining():
  • Concatenates elements into a single String with a delimiter:
    					String joinedNames = people.stream()
            .collect(Collectors.joining(", "));
  • summingInt(), summingLong(), summingDouble():
  • Calculates the sum of elements:
    					int totalAge = people.stream()
  • averagingInt(), averagingLong(), averagingDouble()
  • Calculates the average of elements:
    					double averageAge = people.stream()
  • counting():
  • Counts the number of elements:
    					long numberOfPeople = people.stream()
  • maxBy() and minBy():
  • Finds the maximum and minimum elements based on a comparator:
    					Optional<Person> oldestPerson = people.stream()
  • partitioningBy():
  • Partitions elements into two groups based on a predicate:
    					Map<Boolean, List<Person>> partitioned = people.stream()
            (p -> p.getAge() >= 18));
  • groupingBy():
  • Groups elements into a Map based on a classification function:
    					Map<Boolean, List<Person>> partitioned = people.stream()
            (p -> p.getAge() >= 18));
  • mapping():
  • Maps and collects elements:
    					List<String> upperCaseNames = people.stream()
        (Person::getName, Collectors.toList()));
    These are just some of the common use cases for the Collectors class. You can combine and customize these operations to suit your specific needs when working with streams in Java. The Collectors class is a powerful tool for stream processing, simplifying the process of collecting and processing data in a functional and declarative style.

    Share on: