Java 用于合并同一地图对象上的字符串列表的流选项

Java streaming options to merge the list of string on the same map object

我有从地图中获取不同值的用例。有没有办法使用流

Sample Model data set = {"Ford":{"hatchback", "sedan", "TEST"}, "Honda":{"hatchback", "sedan"}, "Toyota":{"hatchback", "sedan", "TeST2"}}

for (Entry<String, Set<String>> model: models.entrySet()) {
modelList.addAll(model.getValue()); 
}


Final List: {"hatchback", "sedan", "TEST", "TeST2"}

你可以像这样使用 .flatMap() 和 .collect()

为展示而准备的数据:

    HashMap<String, Set<String>> models = new HashMap<>();
    models.put("Ford", Set.of("hatchback", "sedan", "TEST"));
    models.put("Honda", Set.of("hatchback", "sedan"));
    models.put("Toyota", Set.of("hatchback", "sedan", "TeST2"));

在流中使用 .flatMap() 和 .collect()

    Set<String> uniqueModels = models.entrySet().stream()
            .flatMap(entry -> entry.getValue().stream())
            .collect(Collectors.toSet());

    // This will print "[TEST, sedan, hatchback, TeST2]"
    System.out.println(uniqueModels); 
        List<String> unique=set.stream().flatMap(map->map.values().stream()).flatMap(list->list.stream()).distinct().collect(Collectors.toList());