如何获取指定字段值最大的对象列表中的元素。

huangapple go评论85阅读模式
英文:

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 &amp; setter
}

List&lt;MyObj&gt; list = Arrays.asList(
        new MyObj(&quot;a&quot;, 1),
        new MyObj(&quot;b&quot;, 1),
        new MyObj(&quot;c&quot;, 2),
        new MyObj(&quot;d&quot;, 2),
        new MyObj(&quot;e&quot;, 3),
        new MyObj(&quot;f&quot;, 3)
);
// how to get the objs which value is max, here is MyObj(&quot;e&quot;, 3) and MyObj(&quot;f&quot;, 3)
List&lt;MyObj&gt; 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&lt;MyObj&gt; maxList = list.stream()
        .filter(obj -&gt; obj.getValue() == maxValue)
        .collect(Collectors.toList());

huangapple
  • 本文由 发表于 2020年9月8日 12:03:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/63786933.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定