java8⽤Stream查List对象某属性是否有重复
java8⽤Stream查List对象某属性是否有重复
Java8开发中,针对List对象集合,常需要判断某个属性是否存在重复值。⽤Stream流处理能⽅便的得到结果。练习⼀下stream的⼀些⽤法。
测试⽰例Java代码
@Test
public void t2() {java stream
List<User> list = new ArrayList<>();
User user1 = new User("zhangsan", "beijing", 30);
User user2 = new User("zhangsan", "beijing", 40);
User user3 = new User("lisi", "shanghai", 35);
User user4 = new User("lisi", "shanghai", 28);
User user5 = new User("lisim", "shanghai", 32);
list.add(user1); list.add(user2);list.add(user3); list.add(user4);list.add(user5);
System.out.println("原始数据:"+list);
//判断姓名是否有重复,练习使⽤java8的stream⽅法
//⽅法1. distinct, 直接⽐较⼤⼩,只知道是否有重复
List<String> collect1 = list.stream().map(User::getName).distinct().List());
System.out.println(collect1.size()!=list.size()?"⽅法1-姓名有重复":"⽆重复");
//⽅法2.⽤户姓名计数
Map<Object, Long> collect2 = list.stream().collect(
System.out.println("姓名重复计数情况:"+collect2);
/
/筛出有重复的姓名
List<Object> collect3 = collect2.keySet().stream().
filter(key -> (key) > 1).List());
//可以知道有哪些姓名有重复
System.out.println("⽅法2-重复的姓名: "+collect3);
//⽅法3,对重复的姓名保留计数
List<Map<String, Long>> collect4 = collect2.keySet().stream().
filter(key -> (key) > 1).map(key -> {
Map<String, Long> map = new HashMap<>();
map.put((String) key, (key));
return map;
}).List());
System.out.println("⽅法3-重复的姓名及计数:"+collect4);
}
运⾏结果,⽅便验证是否是需要的样⼦。
原始数据:[User(name=zhangsan, address=beijing, age=30), User(name=zhangsan, address=beijing, age=40), User(name=lisi, address=shanghai, age=35), User(name=lisi, address=shanghai, age=28), User(name=lisim,
address=shanghai, age=32)]
⽅法1-姓名有重复
姓名重复计数情况:{lisi=2, zhangsan=2, lisim=1}
⽅法2-重复的姓名 : [lisi, zhangsan]
⽅法3-重复的姓名及计数:[{lisi=2}, {zhangsan=2}]

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。