简体   繁体   中英

How do I use Java streams to convert a set of strings to a set of maps?

Given a Set<String> , how do I use Java streams to create a Set<Map> where each string s becomes a map with a single key/value pair with key "x" and value s ?

Something like this, but I need one more level of collect in there somewhere: set.stream().collect(Collectors.toMap(p->"x", v->v))

You can use Collections.singletonMap to map each String to a Map<String,String> . Then you can collect the Map s into a Set :

Set<Map<String,String>> mset = set.stream()
                                  .map(s -> Collections.singletonMap("x",s))
                                  .collect(Collectors.toSet());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM