stream 取最大对象、取最大值

    private static List<Person> personList = new ArrayList<>();
    private static List<Person> personList2 = new ArrayList<>();
    private static List<Person> personList3 = new ArrayList<>();
    private static List<Person> personList4 = new ArrayList<>();
    private static List<Person> personList5 = new ArrayList<>();

    static {
        personList.add(new Person("12", "xx", 26));
    }

    static {
        personList2.add(new Person("13", "xx", 24));
        personList2.add(new Person("14", "xx", 28));
    }

    static {
        personList3.add(new Person("13", "xx", 24));
        personList3.add(new Person("14", "xx", 28));
        personList3.add(new Person("14", "xx", 28));
    }

    static {
        personList4.add(new Person("12", "xx", 26));
        personList4.add(new Person("13", "xx", 24));
        personList4.add(new Person("14", "xx", 28));
        personList4.add(new Person("15", "xx", 25));
    }

    static {
        personList5.add(new Person("12", "xx", 26));
        personList5.add(new Person("13", "xx", 24));
        personList5.add(new Person("14", "xx", 28));
        personList5.add(new Person("15", "xx", 25));
        personList5.add(new Person("16", "xx", 22));
    }
    @Test
    public void test7() {

        SmallGroup smallGroup1 = new SmallGroup(personList);

        SmallGroup smallGroup2 = new SmallGroup(personList2);
        SmallGroup smallGroup3 = new SmallGroup(personList3);
        SmallGroup smallGroup4 = new SmallGroup(personList4);
        SmallGroup smallGroup5 = new SmallGroup(personList5);

        List<SmallGroup> list = new ArrayList();
        list.add(smallGroup1);
        list.add(smallGroup2);
        list.add(smallGroup3);
        list.add(smallGroup4);
        list.add(smallGroup5);

        Integer maxint = list.stream().map(s -> s.getDet().size()).max((x, y) -> x.compareTo(y)).get();
        System.out.println("maxint = " + maxint);


        Integer maxint2 = personList5.stream().filter(p -> p.getAge() != null).map(Person::getAge).sorted((a1, a2) -> a2.compareTo(a1)).findFirst().get();
        System.out.println("maxint2 = " + maxint2);

        Integer maxint3 = personList5.stream().map(Person::getAge).max(Integer::compareTo).get();
        System.out.println("maxint3 = " + maxint3);

        //可以转换成double
        double maxint4 = personList5.stream().mapToDouble(Person::getAge).max().getAsDouble();
        System.out.println("maxint4 = " + maxint4);

        //获取最大的对象
        Person person = personList5.stream().max((p1, p2) -> p1.getAge() - p2.getAge()).get();
        System.out.println("person = " + person);
    }
maxint = 5
maxint2 = 28
maxint3 = 28
maxint4 = 28.0
person = Person(id=14, name=xx, age=28)

你可能感兴趣的:(java)