1、使用Stream 方法 使用JDK1.8及以上
/*** Java合并两个List并去掉重复项的几种做法* @param args*/public static void main(String[] args) {String[] str1 = {"1", "2", "3", "4", "5", "6"};List<String> list1 = new ArrayList<>(Arrays.asList(str1));String[] str2 = {"4", "5", "8", "10", "3"};List<String> list2= new ArrayList<>(Arrays.asList(str2));// 去重信息List<String> collect= Stream.of(list1,list2).flatMap(Collection::stream).distinct().collect(Collectors.toList());for (String str:collect) {log.info("测试结果:"+str);}
}
运行结果如下:
2、HashSet集合的方式进行去重
/*** Java合并两个List并去掉重复项的几种做法* @param args*/public static void main(String[] args) {String[] str1 = {"1", "2", "3", "4", "5", "6"};List<String> list1 = new ArrayList<>(Arrays.asList(str1));String[] str2 = {"4", "5", "8", "10", "3"};log.info("=====================HashSet去重操作======================");Set<String> set = new HashSet<>(list1);set.addAll(list2);List<String> list = new ArrayList<>(set);log.info("hashSet去重:"+list);}
运行结果如下: