在对象列表中查找元素的最大大小

@Data

class Person {


    private String fname;

    private String lname;


    private List<String> friends;

    private List<BigDecimal> ratings;


    ...

}


@Data

class People {


    private List<Person> people;


    ...

}

假设我有上述课程,并且需要弄清楚一个人拥有的最多朋友数量是多少。我知道 pre-streams 的做法......通过循环列表中的每个元素并检查friends.size() 是否大于当前存储的最长列表的数量。有没有办法用流简化代码?像这个答案?


aluckdog
浏览 174回答 3
3回答

四季花海

根据依赖于 的大小的比较器计算Person包含的最大值:PeoplePerson.getFriends()Optional<Person> p = people.getPeople()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.max(Comparator.comparingInt(p -> p.getFriends()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.size()));请注意,您还可以仅检索不与 Person 关联的朋友的最大数量:OptionalInt maxFriends = people.getPeople()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.mapToInt(p -> p.getFriends()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.size())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.max();

幕布斯6054654

您可以在Person类中声明以下方法:public int getNumberOfFriends(){&nbsp; &nbsp;return friends.size();}然后在这样的流中使用它:Optional <Person> personWithMostFriends = people.stream().max(Comparator.comparingInt(Person::getNumberOfFriends));通过这种方法,您将获得Person最多朋友的对象,而不仅仅是某人建议的最大朋友数。

ibeautiful

你的问题已经回答了。但我添加这个是为了一件事。如果您的人员列表很大,并且您有多核电脑并且您想有效地使用它,那么请使用parallelstream()。得到人:Person person = people.getPeople().parallelStream().max(Comparator.comparingInt(p-> p.getFriends().size())).orElse(null);获取尺寸:int size = people.getPeople().parallelStream().mapToInt(p -> p.getFriends().size()).max().orElse(0);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java