Java8 threads: filter the map

I am trying to figure out how to use Java8 threads for the following case:

Suppose I have the following Map:

Map<String,String[]> map = { { "01": {"H01","H02","H03"}, {"11": {"B11","B12","B13"}} };

And the desired result:

map = { {"01": {"H02"}, {"11": {"B11"}};

My attempt:

map.entrySet().stream() //
        .flatMap(entry -> Arrays.stream(entry.getValue()) //
        .filter(channel -> Channel.isValid(channel))
        .collect(Collectors.toMap()));
+4
source share
1 answer

There are a couple of issues with your current approach.

  • There is no toMap method with a signature toMap()to display a compilation error.
  • flatMap expects a function with a type Tand returns Stream<R>, while you are trying to pass the map as a return value, to also throw a compilation error.

Instead, it seems that you want something like this:

Map<String, List<String>> resultSet = map.entrySet()
                .stream() //
                .flatMap(entry -> Arrays.stream(entry.getValue())
                        .filter(Channel::isValid)
                        .map(e -> new AbstractMap.SimpleEntry<>(entry.getKey(), e)))
                .collect(Collectors.groupingBy(AbstractMap.SimpleEntry::getKey,
                        Collectors.mapping(AbstractMap.SimpleEntry::getValue, 
                               Collectors.toList())));

or a much simpler solution:

map.entrySet()
   .stream() //
   .collect(Collectors.toMap(Map.Entry::getKey, 
               a -> Arrays.stream(a.getValue())
                          .filter(Channel::isValid)
                          .collect(Collectors.toList())));
+1
source

Source: https://habr.com/ru/post/1696123/


All Articles