-2

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

xmcx
  • 283
  • 3
  • 18
  • You were already given the answer below in a link to a duplicate question used to close your [prior deleted question](https://stackoverflow.com/questions/63786702/how-to-get-elements-with-max-value-from-a-list?noredirect=1#63786702). Why are you asking again, when the answers have been already given to you? – Hovercraft Full Of Eels Sep 08 '20 at 23:25
  • I read the [link](https://stackoverflow.com/questions/19338686/java-getting-max-value-from-an-arraylist-of-objects), but it is to get the maximum value of MyObj.value, not all MyObj objects with the maximum value. I thought I didn't describe it clearly, so I asked a new question again. – xmcx Sep 09 '20 at 08:50

1 Answers1

2

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());
Bohemian
  • 412,405
  • 93
  • 575
  • 722
ImtiazeA
  • 1,272
  • 14
  • 19