Java 8-Flatten Map with Lists

I have a structure like Map <String,List<Map<String,Object>>. I want to apply a function to a map as follows. The method uses a key and uses a <String,Object>list map . Each key has several cards <String,Object>in the list. How to apply a process method to a map key for each map value <String,Object>? I was able to use forEach loops (see below), but I have a feeling that this is not the best way to solve the problem in a functional way.

TypeProcessor p=new TypeProcessor.instance();

//Apply this function to the key and each map from the list
// The collect the Result returned in a list.
Result process(String key, Map<String,Object> dataPoints);
List<Result> list = new ArrayList<>();
map.forEach(key,value) -> {
  value.forEach(innerVal -> {
    Result r=p.process(key,innerVal);
    list.add(r):
  });
});
+4
source share
2 answers

It seems that from your code, you want to apply processfor everything Mapso that you can do it like this:

 List<Result> l = map.entrySet()
            .stream()
            .flatMap(e -> e.getValue().stream().map(value -> process(e.getKey(), value)))
            .collect(Collectors.toList());
+2
source

, map key, foreach. map, , List:

List<Result> list = 
    map.get(key)
       .stream()
       .map(v -> p.process(key,v))
       .collect(Collectors.toList());
+2

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


All Articles