distinct()使用hashCode()和equals()方法来获取不同的元素。因此,我们的类必须实现hashCode()和equals()方法。
如果distinct()正在处理有序流,那么对于重复元素,将保留以遭遇顺序首先出现的元素,并且以这种方式选择不同元素是稳定的。在无序流的情况下,不同元素的选择不一定是稳定的,是可以改变的。distinct()执行有状态的中间操作。
在有序流的并行流(parallelStream)的情况下,保持distinct()的稳定性是需要很高的代价的,因为它需要大量的缓冲开销。如果我们不需要保持遭遇顺序的一致性,那么我们应该可以使用通过BaseStream.unordered()方法实现的无序流。
1.排序示例
List<String> list= Arrays.asList("a","bb","bb","qw","oo","oo","pp");
long lsCount= list.stream().distinct().count();
System.out.println("集合长度:"+lsCount);
//去重后获取新的集合
list=list.stream().distinct().collect(Collectors.toList());
//新集合遍历
list.forEach(System.out::println);
2.对象排序示例
对象必须重写 hashCode()和equals()方法。
import java.util.Objects;
public class Person {
private String name;
private Integer age;
private Integer sex;
private Double height;
public Person(String name, Integer age, Integer sex,Double height) {
this.name = name;
this.age = age;
this.sex = sex;
this.height=height;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public Double getHeight() {
return height;
}
public void setHeight(Double height) {
this.height = height;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return name.equals(person.name) && age.equals(person.age);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
进行排序
//对象实体
List<Person> people= Arrays.asList(
new Person("aa",18,1,12.0),
new Person("bb",18,1,13.0),
new Person("aa",18,1,14.0),
new Person("cc",23,1,15.0),
new Person("cc",18,1,16.0),
new Person("cc",18,1,17.0),
new Person("dd",19,1,18.0),
new Person("aa",18,1,19.0),
new Person("bb",18,1,113.0),
new Person("aa",18,1,114.0),
new Person("cc",23,1,115.0),
new Person("cc",18,1,116.0),
new Person("cc",18,1,117.0),
new Person("dd",19,1,118.0),
new Person("aa",18,1,122.0),
new Person("bb",18,1,123.0),
new Person("aa",18,1,124.0),
new Person("cc",23,1,125.0),
new Person("cc",18,1,16.0),
new Person("cc",18,1,127.0),
new Person("dd",19,1,128.0));
long perCount= people.stream().distinct().count();
System.out.println("Person集合长度:"+perCount);
people.stream().distinct().forEach(person -> {
System.out.println("Person:"+String.format("姓名:%s;年龄:%s;性别:%s;身高:%s;",person.getName(),person.getAge(),
person.getSex(),person.getHeight()));
});
输出结果:
Person集合长度:5
Person:姓名:aa;年龄:18;性别:1;身高:12.0;
Person:姓名:bb;年龄:18;性别:1;身高:13.0;
Person:姓名:cc;年龄:23;性别:1;身高:15.0;
Person:姓名:cc;年龄:18;性别:1;身高:16.0;
Person:姓名:dd;年龄:19;性别:1;身高:18.0;