前言
工作中很多時(shí)候需要用到合并兩個(gè)List并去除其中的重復(fù)內(nèi)容,這是一個(gè)很簡(jiǎn)單的操作,實(shí)現(xiàn)的方法也多種多樣。
下面以具體實(shí)例展示給大家~
一、使用stream方式進(jìn)行去重(需要jdk1.8及以上)
String[] arr1 = {"a", "b", "c", "d", "e", "f"};
List<String> listA = new ArrayList<>(Arrays.asList(arr1));
String[] arr2 = {"d", "e", "f", "g", "h"};
List<String> listB = new ArrayList<>(Arrays.asList(arr2));
List<String> collect = Stream.of(listA, listB)
.flatMap(Collection::stream)
.distinct()
.collect(Collectors.toList());
可以很清楚的看出通過Stream完成的代碼看上去更加簡(jiǎn)潔流暢文章來源:http://www.zghlxwxcb.cn/news/detail-516316.html
二、使用HashSet集合的方式進(jìn)行去重
String[] arr1 = {"a", "b", "c", "d", "e", "f"};
List<String> listA = new ArrayList<>(Arrays.asList(arr1));
String[] arr2 = {"d", "e", "f", "g", "h"};
List<String> listB = new ArrayList<>(Arrays.asList(arr2));
Set<String> set = new HashSet<>(listA);
set.addAll(listB);
List<String> list = new ArrayList<>(set);
System.out.println(list);
這樣做后的list就是合并并去重后的結(jié)果文章來源地址http://www.zghlxwxcb.cn/news/detail-516316.html
到了這里,關(guān)于【Java】Java合并兩個(gè)List后并去掉重復(fù)項(xiàng)的幾種做法的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!