How do aggregate operations on Java threads work?

In the following excerpt from Java tutorials in aggregate operations, we map the names of people to their genders.

Map<Person.Sex, List<String>> namesByGender =
roster
    .stream()
    .collect(
        Collectors.groupingBy(
            Person::getGender,                      
            Collectors.mapping(
                Person::getName,
                Collectors.toList())));

I understand that the collection operation:
1) Groups each person in the stream according to the result of getGender.
2) maps each person to the result of getName.
3) Generates a list of results and.
4) Creates a card whose keys are gender of persons and whose data values ​​are the names of persons.

My questions:
1) In what order do Collectors act?
2) What are the periodic types between them?

+2
source share
2 answers

groupingBy's, :

Supplier<A> downstreamSupplier = downstream.supplier();
        BiConsumer<A, ? super T> downstreamAccumulator = downstream.accumulator();
        BiConsumer<Map<K, A>, T> accumulator = (m, t) -> {
            K key = Objects.requireNonNull(classifier.apply(t), "element cannot be mapped to a null key");
            A container = m.computeIfAbsent(key, k -> downstreamSupplier.get());
            downstreamAccumulator.accept(container, t);
        };

-. Person::getGender.

-. , ArrayList::new

-. Person::getName List::add

ArrayList::new List::add CollectorImpl, Collectors.toList

+1

"", . , , .

, Stream.collect.

Collector :

A Collector , , , , . :

  • (())
  • (accumulator())
  • (())
  • (())

, toList() , ArrayList::new , List::add List::addAll , , , , .

Collectors.mapping , , . , . mapper .

, Collectors.groupingBy . , HashMap. , Map.computeIfAbsent, , , , . Map.merge , , .

, , . ,

Map<Person.Sex, List<String>> namesByGender = new HashMap<>();
for(Person p: roster)
    namesByGender.computeIfAbsent(p.getGender(), k -> new ArrayList()).add(p.getName());
+1

Source: https://habr.com/ru/post/1688836/


All Articles