To change the structure of value in map using Java8 Stream stream operation

Map < String,List < String > replace with Map < String,Java >

the original data structure is as follows:
Map < String,String > map=new LinkedMultiValueMap < > ();
map.add ("java", "1.7");
map.add ("java", "1.8");
the map after adding data is: < String,List < String > > the same key value is collected by list
now want to use stream stream operation, will:
Map < String,List < String > map-> Map < String,Java > map

The structure of

Java is as follows:
public class Java {

private List<String> versions;

}

Oct.19,2021

Thank you for the invitation

according to the description of the subject, I feel that it is actually a process of transforming map into map . What can be seen is value , but key remains unchanged. Here map also provides a disguised way to transform the data in map into stream , and there is no direct map.stream () method.

the map loop used entrySet of map , but the entrySet here is a collection, so you can use stream

.
Map<String,List<String>> map = new HashMap<>();
map.put("java", Arrays.asList("1.7", "1.8"));
map.entrySet().stream()

at this time, the data in the stream map.entrySet (). Stream () is Map.Entry < String,List < String > > . Now, in fact, we want to convert Map.Entry < String,List < String > > into Map < String,Java > . Since the final result is collected with map , we can only collect (Collectors.toMap ()) ).

Map<String, Java> collect = map.entrySet().stream()
                .collect(Collectors.toMap(
                        stringListEntry -> stringListEntry.getKey(), 
                        stringListEntry -> new Java(stringListEntry.getValue())));

Collectors.toMap the method of two parameters, the first parameter represents how to obtain key , the second represents how to obtain value , because key has not changed, so directly take the key, value of entry into Java object, so I wrote a constructor (I annotated it with lombok )

    @Getter
    @Setter
    @AllArgsConstructor
    public static class Java{
        private List<String> versions;
    }

that's about it, for reference only ^ _ ^

Menu