Search code examples
javajava-8java-streamcollectors

Collecting the returned HashMaps into one with new identifier in Java-8


I'm not well versed with Java Stream collector framework, I want to solve a real world problem and want to use streams.

Here is simplified hypothetical scenario of the actual problem.

I have an interface whose implementations return a HashMap<Integer, Object>

interface myInterface{
  String getImplKey(); //just adding it for classification.
  Map<Integer, Object> getImplDataWithDataKeys(); //this is main functionality but different implementations. 
}

Now if I auto wire this interface list in spring, spring will provide all the implementation in one place

I want to write a code where I can collect the data from all the implementations and return into a HashMap, Map will also tell which implementation the data belongs to.

List<myInterface> myinterfaceImpls;

getAll Data(){
        myinterfaceImpls.stream()..... 
       call myInterfaceImpl.getDataWithDataKeys() ... 
       collect into Map with myInterface.getIdentifierKey() as key. and above myInterfaceImpl.getDataWithDataKeys() as value
get something in form Map<String,Map<Integer,Object>>

Solution

  • OK, based on your comment you can do like this:

    myinterfaceImpls.stream()
                     .flatMap(myImpl->myImpl.getDataWithDataKeys().entrySet().stream())
                     .collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue));
    

    However, if your concern is about a duplicate key, you can perform toMap collector with a merge function.