We have:

Map<String, List<Object>> map = fillMap(); 

It is necessary to convert it as elegantly as possible to a List<Pair<String, Object>> using the Stream API ( Pair from apache lang3).

For example, it was:

 [ a=[obj1,obj2,obj3], b=[obj4,obj5], c=[obj6,obj7] ] 

I want to get:

 [ Pair{a,obj1}, Pair{a,obj2}, Pair{a,obj3}, Pair{b,obj4}, Pair{b,obj5}, Pair{c,obj6}, Pair{c,obj7} ] 

    1 answer 1

    You can use the flatMap operation (instead of Pair - AbstractMap.SimpleEntry ), it accepts the function that returns Stream and embeds the elements of the returned stream into the main:

      Map<String, List<String>> map = new HashMap<>(); map.put( "a", Arrays.asList( "obj1", "obj2", "obj3" ) ); map.put( "b", Arrays.asList( "obj4", "obj5" ) ); map.put( "c", Arrays.asList( "obj6", "obj7" ) ); System.out.println( map ); List<Map.Entry<String, String>> list = map.entrySet().stream().flatMap( entry -> entry.getValue().stream() .map( listElement -> new AbstractMap.SimpleEntry<>( entry.getKey(), listElement ) ) ).collect( Collectors.toList() ); System.out.println( list );