Created
October 17, 2017 19:13
-
-
Save sermojohn/e8828288172d5c9e85046c4b25a7d425 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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