英文:
How to get the elements which specified field value value is max from object list
问题
如何从对象列表中获取特定字段值为最大的元素?
public class MyObj {
    private String name;
    private int value;
    // getter & setter
}
List<MyObj> list = Arrays.asList(
        new MyObj("a", 1),
        new MyObj("b", 1),
        new MyObj("c", 2),
        new MyObj("d", 2),
        new MyObj("e", 3),
        new MyObj("f", 3)
);
// 如何获取值最大的对象,这里是 MyObj("e", 3) 和 MyObj("f", 3)
List<MyObj> maxList = //todo ;
注意:不获取最大值本身
英文:
How to get the elements which specified field value value is max from object list?
public class MyObj {
    private String name;
    private int value;
    // getter & setter
}
List<MyObj> list = Arrays.asList(
        new MyObj("a", 1),
        new MyObj("b", 1),
        new MyObj("c", 2),
        new MyObj("d", 2),
        new MyObj("e", 3),
        new MyObj("f", 3)
);
// how to get the objs which value is max, here is MyObj("e", 3) and MyObj("f", 3)
List<MyObj> maxList = //todo ;
Note: not to get the max value
答案1
得分: 2
这将完成任务。首先根据值获取最大值,然后根据该值筛选列表。
int maxValue = list.stream()
        .mapToInt(MyObj::getValue)
        .max().orElse(Integer.MIN_VALUE);
List<MyObj> maxList = list.stream()
        .filter(obj -> obj.getValue() == maxValue)
        .collect(Collectors.toList());
英文:
This will do the job. It first gets the max value based on the value and filters the list based on that value.
int maxValue = list.stream()
        .mapToInt(MyObj::getValue)
        .max().orElse(Integer.MIN_VALUE);
List<MyObj> maxList = list.stream()
        .filter(obj -> obj.getValue() == maxValue)
        .collect(Collectors.toList());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论