Search code examples
javajava-stream

How to generate map with included map basing on list of integers?


I have list of ids like

List<Integer> ids = new ArrayList(){1,2,3};

I need to transform this to the map of next structure:

Map<Integer, Map<String, String>> where keys will be ids from the list and map will be just empty map. Of course I can create new map, after that I can iterate over the list and to put id and new HashMap<String,String> to that new map. But is it possible to do that in one stream? Using generate() and collect() methods?


Solution

  • You can use Collectors.toMap(...)

    ids.stream().collect(Collectors.toMap( 
        Function.identity(), 
        id -> new HashMap<String, String>() 
    ));
    

    Collectors.toMap requires two parameters: firstly, a key mapper, in our case, we'll use the current id from the stream, so id -> id or simply Function.identity().

    Then, for the value mapper, for each id, we are creating a new HashMap(), Additionally, you can declare it as __ -> new HashMap<String, String>() (using "__" as the name of the element from the steram would suggest you are not interested in its value, and all the value mappers are returning the same).