Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

2019/12/20--对象中某属性的求和 #37

Open
lq920320 opened this issue Dec 20, 2019 · 0 comments
Open

2019/12/20--对象中某属性的求和 #37

lq920320 opened this issue Dec 20, 2019 · 0 comments

Comments

@lq920320
Copy link
Owner

lq920320 commented Dec 20, 2019

public class ObjectPropertySumTest {


    @Data
    private class Student {
        private String name;
        private Integer age;
    }


    @Test
    public void objectPropertySum() {
        List<Student> students = buildTestData();
        // 7
        System.out.println(students.size());
        // 方式一:
        int ageSum1 = students.stream().mapToInt(Student::getAge).sum();
        // 70
        System.out.println("年龄总和" + ageSum1);
        // 方式二:
        int ageSum2 = students.stream().map(Student::getAge).reduce(Integer::sum).orElse(0);
        // 70
        System.out.println("年龄总和" + ageSum2);
    }

    private List<Student> buildTestData() {
        return new ArrayList<Student>() {{
            add(new Student() {{
                setName("A");
                setAge(10);
            }});
            add(new Student() {{
                setName("B");
                setAge(10);
            }});
            add(new Student() {{
                setName("C");
                setAge(10);
            }});
            add(new Student() {{
                setName("D");
                setAge(10);
            }});
            add(new Student() {{
                setName("E");
                setAge(10);
            }});
            add(new Student() {{
                setName("F");
                setAge(10);
            }});
            add(new Student() {{
                setName("G");
                setAge(10);
            }});
        }};

    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant