[英]How to convert Map<String, List<String>> to Set<String> using streams?
I'm trying to convert Map> to a List/Set of Strings in single line but couldn't do it unless I use traditional forEach for map.我正在尝试将 Map> 转换为单行的列表/字符串集,但除非我对地图使用传统的 forEach,否则无法做到这一点。 Is anyone aware to do it in single line using streams.
是否有人知道使用流在单行中执行此操作。
import java.util.*;
public class StreamDemo {
public static void main(String[] args) {
HashMap<String, List<String>> map = new HashMap<>();
ArrayList<String> s1 = new ArrayList<>();
map.put("A", Arrays.asList("A1, A2"));
map.put("B", Arrays.asList("B1, B2"));
map.put("C", Arrays.asList("C1, C2"));
Set<String> stringValues = new HashSet<>();
// LOGIC TO GET ALL VALUES A1, A2, B1, B2, C1, C2 INTO stringValues
System.out.println(stringValues);
// Expected output
// [A1, A2, B1, B2, C1, C2]
}
}
you could use the following stream which basically streams over your values and collect their items inside of a HashSet
but note that the HashSet
doesn't guarantee sorting.您可以使用以下流,它基本上流过您的值并在
HashSet
收集它们的项目,但请注意HashSet
不保证排序。 For that you'd want to use TreeSet::new
in the end为此,您最终要使用
TreeSet::new
Set<String> stringValues = map.values()
.stream()
.flatMap(List::stream)
.collect(Collectors.toCollection(HashSet::new));
不使用流的解决方案可以更简单:
map.values().forEach(l -> l.forEach(stringValues::add));
Try the below code:试试下面的代码:
HashMap<String, List<String>> map = new HashMap<>();
ArrayList<String> s1 = new ArrayList<>();
map.put("A", Arrays.asList("A1, A2"));
map.put("B", Arrays.asList("B1, B2"));
map.put("C", Arrays.asList("C1, C2"));
HashSet<String> strings = new LinkedHashSet<>();
map.values().stream().sequential().forEach(value -> {
value.forEach(value1 -> {
strings.add(value1);
});
});
System.out.println(strings);
Since your expected output is [A1, A2, B1, B2, C1, C2]
, use LinkedHashSet
instead of a HashSet
.由于您的预期输出是
[A1, A2, B1, B2, C1, C2]
,请使用LinkedHashSet
而不是HashSet
。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
public class Main {
public static void main(String[] args) throws InterruptedException {
HashMap<String, List<String>> map = new HashMap<>();
ArrayList<String> s1 = new ArrayList<>();
map.put("A", Arrays.asList("A1, A2"));
map.put("B", Arrays.asList("B1, B2"));
map.put("C", Arrays.asList("C1, C2"));
Set<String> stringValues = new LinkedHashSet<>();
map.values().forEach(list -> list.forEach(stringValues::add));
System.out.println(stringValues);
}
}
Output:输出:
[A1, A2, B1, B2, C1, C2]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.