javalambdajava-8

Java 8 -Flatten Map with Lists


I have a structure such as Map<String,List<Map<String,Object>>. I want to apply a function to the map as follows. The method takes a key and uses a Map<String,Object> of the list. Each key has several Map<String,Object> in the list. How can I apply the process method to the map's key for each value of Map<String,Object>? I was able to use to forEach loops(see below) but I have a feeling 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):
  });
});

Solution

  • It seems from your code that you want to apply process for the entire Map, so you could do it like this:

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