1.使用Collectors.collectingAndThen链式去重
代码:
public class Person {
private String name;
private Integer id;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", id=" + id +
", age=" + age +
'}';
}
}
main:
public class TestMap2 {
public static void main(String[] args) {
List<Person> people = new ArrayList<>();
Person p111 = new Person();
p111.setId(111);
p111.setName("Yang");
p111.setAge(31);
people.add(p111);
Person p112 = new Person();
p112.setId(111);
p112.setName("Yang");
p112.setAge(31);
people.add(p112);
Person p113 = new Person();
p113.setId(112);
p113.setName("Liu");
p113.setAge(22);
people.add(p113);
System.out.println(people);
people = people.stream().collect(
collectingAndThen(
toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getId))), ArrayList::new));
System.out.println(people);
}
}
结果:
[Person{name='Yang', id=111, age=31}, Person{name='Yang', id=111, age=31}, Person{name='Liu', id=112, age=22}]
[Person{name='Yang', id=111, age=31}, Person{name='Liu', id=112, age=22}]
或者可以利用map也可以:
people = people.stream().collect(
collectingAndThen(
toMap(Person::getId,Function.identity(),(k1,k2)->k1), map->map.values().stream()
.collect(Collectors.toList())));
或:
people = people.stream().collect(
collectingAndThen(
toMap(Person::getId,Function.identity(),(k1,k2)->k1), map-> new ArrayList<>(map.values())));
或者不用链式也可以分开:
Map<Integer,Person > storeAttrMap = people.stream().collect(Collectors.toMap(Person::getId, Function.identity(), (k1,k2)->k1));
people = new ArrayList<>(storeAttrMap.values());
Collectors.collectingAndThen()
Collectors.collectingAndThen()
函数应该最像 map and reduce
了,它可接受两个参数,第一个参数用于 reduce
操作,而第二参数用于 map
操作。
也就是,先把流中的所有元素传递给第一个参数,然后把生成的集合传递给第二个参数来处理。
例如下面的代码
把 [1,2,3,4] 这个集合传递给 v -> v * 2 lambda表达式,计算得出结果为[2,4,6,8]
然后再把 [2,4,6,8]传递给 Collectors.averagingLong 表达式,计算得出 5.0
然后传递给 s -> s * s lambda表达式,计算得到结果为 25.0
代码示例:
@Test
public void collectingAndThenExample() {
List<Integer> list = Arrays.asList(1, 2, 3, 4);
Double result = list.stream().collect(Collectors.collectingAndThen(Collectors.averagingLong(v -> {
System.out.println("v--" + v + "--> " + v * 2);
return v * 2;
}),
s -> {
System.out.println("s--" + s + "--> " + s * s);
return s * s;
}));
System.out.println(result);
}
结果:
v--1--> 2
v--2--> 4
v--3--> 6
v--4--> 8
s--5.0--> 25.0
25.0
了解之后可以看一下
people = people.stream().collect(
collectingAndThen(
toMap(Person::getId,Function.identity(),(k1,k2)->k1), map->map.values().stream()
.collect(Collectors.toList())));
先将people转成Map结构Map<Integer,Person>结构,然后将这个map整体作为一个参数传给第二个lambda表达式,输入参数是第一步传过来的map,然后将其转化为List,这个List就是最终的结果