Stream group - Java Lambda Stream

Java examples for Lambda Stream:Collector

Description

Stream group

Demo Code



//package com.book2s;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Main {
  public static <T, K, V> HashMap<K, HashSet<V>> group(Collection<T> entities, Function<T, K> keyMapper,
      Function<T, V> valueMapper) {
    return entities.stream().collect(Collectors.groupingBy(keyMapper, HashMap::new,
        Collectors.mapping(valueMapper, Collectors.toCollection(HashSet::new))));
  }//w ww .  java  2 s  .co m

  public static <T, K, V> HashMap<K, HashSet<V>> group(T[] entities, Function<T, K> keyMapper,
      Function<T, V> valueMapper) {
    return group(Arrays.asList(entities), keyMapper, valueMapper);
  }
}

Related Tutorials