我正在尝试将 Map> 转换为单行的列表/字符串集,但除非我对地图使用传统的 forEach,否则无法做到这一点。是否有人知道使用流在单行中执行此操作。
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]
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用以下流,它基本上流过您的值并在 a 中收集它们的项目,HashSet但请注意,HashSet不保证排序。为此,您TreeSet::new最终想要使用
Set<String> stringValues = map.values()
.stream()
.flatMap(List::stream)
.collect(Collectors.toCollection(HashSet::new));
Run Code Online (Sandbox Code Playgroud)