Click here to Skip to main content
15,894,646 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I would like to get the highest score group by Id .If two highest score's are same then i would like get the highest score based on lowest Optional ID.
I would like to get it in Java Stream.So far i have a code works.Is there any efficient way to rewrite this code in java stream

Example :

Array List:

ID: 1 Score:80 OptionalId:1
ID: 1 Score:90 OptionalId:2
ID: 1 Score:90 OptionalId:3
ID: 2 Score:80 OptionalId:1
ID: 2 Score:100 OptionalId:3
ID: 2 Score:100 OptionalId:5

The result should be

ID: 1 Score 90 OptionalId:2
ID 2 Score 100 OptionalId:3

What I have tried:

Java
records=record.Person(batchNumber);
List<Person> highestRecords = new ArrayList<>();for(
Person s:records)
  {
if(!highestRecords.isEmpty()) {
    boolean contains = false;
    for(Person ns: new ArrayList<>(highestRecords)) {
        if(s.Id().compareTo(ns.Id()) == 0) {
            contains = true;
            if(s.getScore.compareTo(ns.getScore()) > 0     
    && s.optionalId().compareTo(ns.optionalId()) < 0) {

                highestRecords.remove(ns);
                highestRecords.add(s)       
            }
        }
    }
    if(contains == false) {
        highestRecords.add(s);
    }
}else {
    highestRecords.add(s);
}
  }
}
Posted
Updated 25-Jan-19 12:27pm
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900