美文网首页
jdk8 list新特性demo

jdk8 list新特性demo

作者: itcode | 来源:发表于2019-07-07 19:11 被阅读0次
    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);
    
        }

    相关文章

      网友评论

          本文标题:jdk8 list新特性demo

          本文链接:https://www.haomeiwen.com/subject/efgmzqtx.html