主要实现代码
Listpersons = new ArrayList(); Listids = new ArrayList<>();//用来临时存储person的id persons.add(new Person(1, "name1", 10)); persons.add(new Person(2, "name2", 21)); persons.add(new Person(5, "name5", 55)); persons.add(new Person(3, "name3", 34)); persons.add(new Person(1, "name1", 10)); List personList = persons.stream().filter(// 过滤去重
v -> {
boolean flag = !ids.contains(v.getId());
ids.add(v.getId());
return flag;
}
).collect(Collectors.toList());
System.out.println(personList);
运行后的打印如下.可以看出id为1时的重复数据已经被过滤掉了
[
Person{id=1, name='name1', age=10},
Person{id=2, name='name2', age=21},
Person{id=5, name='name5', age=55},
Person{id=3, name='name3', age=34}
]
person类的代码如下
package com.qcl.demo;
/**
* Created by qcl on 2018/3/26.
*/
public class Person {
private int id;
private String name;
private int age;
public Person() {
}
public Person(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
这只是java8在我们开发时比较常用的一个操作。
如下面这个例子使用也比较普遍
获取person集合中的所有大于18周岁,并排序List persons = new ArrayList();
persons.add(new Person(1, "name1", 10));
persons.add(new Person(2, "name2", 21));
persons.add(new Person(5, "name5", 55));
persons.add(new Person(3, "name3", 34));
persons.add(new Person(4, "name4", 6));
persons.stream()
.filter(p -> p.getAge() >= 18)//获取所有18岁以上的用户
.sorted(Comparator.comparing(Person::getAge))//依年纪升序排序
.sorted(Comparator.comparing(Person::getAge).reversed())//依年纪降序排序
.collect(Collectors.toList())
.forEach(System.out::println);
boolean isAllAdult = persons.stream().
allMatch(p -> p.getAge() > 18);
System.out.println("是否所有的用户都大于18岁" + isAllAdult);
龙华大道1号http://www.kinghill.cn/LongHuaDaDao1Hao/index.html