public static void main(String[] args) {
//jdk8 stream对list数据去重,使用filter()过滤列表,list转map
//去除List中重复的String
List<String> list = new ArrayList<>();
list.add("aaa");
list.add("bbb");
list.add("bbb");
List unique = list.stream().distinct().collect(Collectors.toList());
System.out.println("unique: " + unique);
List<Person> persons = new ArrayList<>();
persons.add(new Person("1", "jack", "boy"));
persons.add(new Person("2", "jack", "boy"));
persons.add(new Person("3", "tom", "boy"));
persons.add(new Person("4", "mary", "girl"));
//根据name去重
List<Person> name = persons.stream().collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName))),
ArrayList::new
));
System.out.println("name: " + name);
//根据name和sex去重
List<Person> nameSex = persons.stream().collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getName() + ";" + o.getSex()))),
ArrayList::new
));
System.out.println("nameSex: " + nameSex);
//filter()过滤列表
List<Person> filterList = persons.stream().filter(person -> person.getSex().equals("girl")).collect(Collectors.toList());
System.out.println("filterList: " + filterList);
//list转map
Map<String,Object> toMap = persons.stream().collect(Collectors.toMap(p->p.getId(),p->p.getName()));
System.out.println("toMap: " + toMap);
}
网友评论