1

I am learning to do thing using Java8 and Stream. I have a problem which I am trying to solve using java8 stream.

I have a Map with type Map<String, List<Integer>> accountMap Data - {0000132861=[6613, 6170, 6206], 0000135932=[6613, 6170, 6206], 0000122989=[6613, 6170, 6206], 0000138372=[3187, 6613, 8167, 6170, 6206], 0000138399=[6613, 6170, 6206]}

I want all the unique integer values inside the Map.value(). Like [3187, 6613, 8167, 6170, 6206]

When I do accountMap.values() I get List<List<Integer>> [[6613, 6170, 6206], [6613, 6170, 6206], [6613, 6170, 6206], [3187, 6613, 8167, 6170, 6206], [6613, 6170, 6206]]

When I do accountUserMap.values().stream().collect(Collectors.toSet()) I get same data type Set<List<Integer>> [[3187, 6613, 8167, 6170, 6206], [6613, 6170, 6206]] But all the duplicate list are dropped.

I want to drop all the duplicate values and want to get Set<Integer> [3187, 6613, 8167, 6170, 6206]

There should be an efficient way to do it without using .forEach() or iterating the list.

Alexis C.
  • 87,500
  • 20
  • 164
  • 172
Bala
  • 615
  • 10
  • 21

2 Answers2

4

You can use flatMap to "flatten" the stream of values:

map.values().stream()
    .flatMap(List::stream)
    .collect(toSet());

Alternatively, you can use the 3-argument collect:

map.values().stream()
    .collect(HashSet::new, Set::addAll, Set::addAll);
Misha
  • 26,303
  • 6
  • 57
  • 74
0

Never used streams myself, but instead of just stream() in your code above, try:

stream().flatMap(p -> p.stream())

to unpack that next list level.

That's what this answer suggests in a similar context

Dmytro Bugayev
  • 496
  • 8
  • 10