0

I have a list like this

[
  {
    "applicationNumber": "100400",
    "points":"20"
  },
  {
    "applicationNumber": "100400",
    "points": "100"
  },
  {
    "applicationNumber": "200543",
    "points": "54"
  },
  {
    "applicationNumber": "200543",
    "points": "23"
  },
  {
    "applicationNumber": "243543",
    "points":"53"
  }
]

stored in variable 'list'

For each applicationNumber I want the maximum points and ignore all remaining from the list .

I want to achieve the same using Java Streams. can anyone help me.

current code I am using, but not getting result.

List<MyClassPOJO> list = someFunction(); 

List<MyClassPOJO> filteredOutput = 
list.stream().max(Comparator.comparing(MyClassPOJO::getPoints)).orElse(null);

with this code I get no function getPoints and filter my data. I am able to do it using for loops.

PS: Thank you in advance.

Eritrean
  • 15,851
  • 3
  • 22
  • 28
david
  • 79
  • 7
  • Edit 1: due to some error , not able to print this..... List list= someFunction(); List filteredOutput = list.stream().max(Comparator.comparing(MyClassPOJO::getPoints)).orElse(null); – david Jun 26 '21 at 12:31

1 Answers1

2

You can first group by your applicationNumber and then take from each group the element with the maximum points

List<MyClassPOJO> filteredOutput = 
     list.stream()
         .collect(Collectors.groupingBy(MyClassPOJO::getApplicationNumber, 
                      Collectors.maxBy(Comparator.comparing(MyClassPOJO::getPoints))))
         .values().stream()
                  .map(Optional::get)
                  .collect(Collectors.toList());
Eritrean
  • 15,851
  • 3
  • 22
  • 28