两个集合{"a","b","c","d","e"},{"d","e","f","g","h"}合并成一个集合,并且去掉重复的
4条回答 默认 最新
- it_hao528 2022-07-18 10:44关注
Set可以自动去重,所以使用Set直接添加数据就可以。
public static void main(String[] args) { List<String> strList1 = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "e")); List<String> strList2 = new ArrayList<>(Arrays.asList("d", "e", "f", "g", "h")); // 创建set并将strList1集合数据赋给set Set<String> set = new HashSet<>(strList1); // 将strList2集合合并到set for (String str : strList2) { set.add(str); } System.out.println("合并后:" + set); }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报