Skip to content

Instantly share code, notes, and snippets.

@sermojohn
Created October 17, 2017 19:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sermojohn/e8828288172d5c9e85046c4b25a7d425 to your computer and use it in GitHub Desktop.
Save sermojohn/e8828288172d5c9e85046c4b25a7d425 to your computer and use it in GitHub Desktop.
import static java.lang.System.out;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class SoAnswer {
public static void main(String[] args) {
List<List<A>> lists = Arrays.asList(generateAs("hello", 1), generateAs("world", 1),
generateAs("hello", 2), generateAs("world", 3));
System.out.println("\ninput");
lists.stream().flatMap(Collection::stream)
.forEach(out::println);
Map<String, List<A>> collect = lists.stream()
.flatMap(Collection::stream)
.collect(Collectors.groupingBy(A::getX));
System.out.println("\noutput");
collect.entrySet().stream()
.forEach(out::println);
}
public static class A{
public String x;
public String y;
public String z;
public String getX() {
return x;
}
@Override
public String toString() {
return "A{" +
"x='" + x + '\'' +
", y='" + y + '\'' +
", z='" + z + '\'' +
'}';
}
}
private static List<A> generateAs(String x, int num) {
return IntStream.range(0, num)
.mapToObj(i -> {
A a = new A();
a.x = x;
return a;
}).collect(Collectors.toList());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment