List集合

您所在的位置:网站首页 字符串合并去重 List集合

List集合

2024-07-16 19:33| 来源: 网络整理| 查看: 265

Java8 利用Stream接口去除集合间重复项

 

java.util.stream Public Interface Stream extends BaseStream

 

Student s1 = new Student(1,20,"Bob"); Student s2 = new Student(2,20,"Jim"); Student s3 = new Student(3,20,"Tom"); Student s4 = new Student(4,20,"Jack"); List listC = new ArrayList(); listC.add(s1); listC.add(s2); listC.add(s3); List listD = new ArrayList(); listC.add(s1); listC.add(s2); listC.add(s4);

① 使用 Set 集合的 内容不重复进行去重

Set set = new HashSet(listC); set.addAll(listD); List list = new ArrayList(set); System.out.println(list);

② 使用 Stream 接口 进行去重

List studentList = Stream.of(listC,listD).flatMap(Collection::stream).distinct().collect(Collectors.toList()); System.out.println(studentList);

 

static  Stream of(T... values)

返回其元素是指定值的顺序排序流。  Stream flatMap(Function


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3