根据指定字段去重,取非指定字段的值:
import java.util.*;
import java.util.stream.Collectors;
@Test
public void test() {
ArrayList<User> objects = new ArrayList<>();
objects.add();
//.....
// 1、反转lists
Collections.reverse(objects);
// 2、stream进行去重(通过id和name) 单个可以直接User::getId
//objects = objects.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(User::getId))), ArrayList::new));
objects = objects.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getId() + ";" + o.getName()))), ArrayList::new));
}
第一步就是先进行反转List,因为stream流去重用的是TreeSet来进行去重的, 先进行反转List就是可以把最新数据放到最前面。