【问题标题】:Combining 3 lists into single collection with unique values将 3 个列表组合成具有唯一值的单个集合
【发布时间】:2019-04-11 14:01:07
【问题描述】:
我在 Java 中有 3 个列表,如下所示
List<Integer> list1 = query1MysqlRepository.getprocessIds();
List<Integer> list2 = query2MysqlRepository.getprocessIds();
List<Integer> list3 = query3MysqlRepository.getprocessIds();
我想将以上三个Integer List 合并到一个集合中,这样该集合不包含任何重复值
Collection = list1 + list2 + list3
请建议在这里可以使用什么集合。
【问题讨论】:
标签:
java
list
arraylist
collections
set
【解决方案1】:
您可以使用不允许重复的Set,只需使用addAll() 方法将List 的所有元素添加到Set:
List<Integer> arr1 = new ArrayList<>(Arrays.asList(1,2,3));
List<Integer> arr2 = new ArrayList<>(Arrays.asList(2,3,4));
List<Integer> arr3 = new ArrayList<>(Arrays.asList(4,5,6));
Set<Integer> hashSet = new HashSet<>();
hashSet.addAll(arr1);
hashSet.addAll(arr2);
hashSet.addAll(arr3);
hashSet.forEach(System.out::println);
输出:
1
2
3
4
5
6
【解决方案2】:
List<Integer> result = Stream.of(list1, list2, list3)
.flatMap(Collection::stream)
.distinct()
.collect(Collectors.toList());
或如果您想避免以后重复添加:-
Set<Integer> result = Stream.of(list1, list2, list3)
.flatMap(Collection::stream)
.collect(Collectors.toSet());