BreenDeen
BreenDeen

Reputation: 760

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):
  });
});

Upvotes: 11

Views: 13844

Answers (2)

Eugene
Eugene

Reputation: 120848

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());

Upvotes: 6

Eran
Eran

Reputation: 393811

Well, assuming map contains key, you don't need any foreach. Just obtain the value from the outer map, stream it, map to your new object and collect to a List:

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

Upvotes: 2

Related Questions