Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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):
  });
});
like image 683
BreenDeen Avatar asked Dec 13 '17 02:12

BreenDeen


People also ask

How do I convert a map to a list of maps?

Method 2: List ListofKeys = new ArrayList(map. keySet()); We can convert Map keys to a List of Values by passing a collection of map values generated by map. values() method to ArrayList constructor parameter.

How do I map an object in Java 8?

Java 8 stream map() map() method in java 8 stream is used to convert an object of one type to an object of another type or to transform elements of a collection. map() returns a stream which can be converted to an individual object or a collection, such as a list.


2 Answers

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());
like image 85
Eugene Avatar answered Sep 20 '22 22:09

Eugene


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());
like image 29
Eran Avatar answered Sep 22 '22 22:09

Eran