Skip to content

Instantly share code, notes, and snippets.

@ShienPro
Created February 20, 2020 07:00
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 ShienPro/822ec0f9d16202096e2973d0d5191ca5 to your computer and use it in GitHub Desktop.
Save ShienPro/822ec0f9d16202096e2973d0d5191ca5 to your computer and use it in GitHub Desktop.
List<Record> records = Arrays.asList(
new Record("组1", "code1", 2),
new Record("组1", "code2", 1),
new Record("组2", "code1", 1),
new Record("组2", "code3", 1)
);
Set<String> codeSet = records.stream().map(Record::getCode).collect(Collectors.toSet());
@SuppressWarnings({"unchecked", "rawtypes"})
Map<String, Map<String, Integer>> map = records.stream()
.collect(Collectors.groupingBy(
Record::getGroup,
Collectors.groupingBy(
Record::getCode,
() -> (Map<String, Integer>) (Map) codeSet.stream().collect(Collectors.toMap(Function.identity(), s -> new int[1])),
Collectors.summingInt(Record::getCount))
));
// {组2={code3=1, code2=0, code1=1}, 组1={code3=0, code2=1, code1=2}}
System.out.println(map);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment