-1

I have an array list consisting of objects defined in the class Result(date, name, grade). I have managed to sort the dataset. However I want there to be no duplicates, only the object with that has highest grade attribute should be left. I have tried several codes but it gets me no where.

The data looks as following now,
DATE NAME GRADE

0612 AA BB 15
0713 AA BB 12
0613 CD E 7
0327 KA BC 23
0903 KA BC 15

But i want it to look like this

0612 AA BB 15
0613 CD E 7
0327 KA BC 23

Result class defined as below

    Result(int date,String name, String grade){  
        this.date=date;  
        this.name=first;  
        this.grade=grade;
    }  
  for (Result element:info) {
          if (!newList.contains(element.name)) {
              newList.add(element);
            }
        }

        for(Result st:newList){  
          System.out.println(st.date+" "+st.name+" " + st.grade);   
        }

    }
}



I have done this, so far. However it does not give me the wanted output.

zara
  • 1
  • 2
  • **I have tried several codes but it gets me no where.** Show it then. Based on your code, I don't see any of your attempt on overriding the contains function, or comparing the elements before inserting it. – YUNG FOOK YONG Oct 26 '22 at 14:02
  • Does this answer your question? [Java Streams – How to group by value and find min and max value of each group?](https://stackoverflow.com/questions/51377851/java-streams-how-to-group-by-value-and-find-min-and-max-value-of-each-group) – 001 Oct 26 '22 at 14:22

1 Answers1

0

You can take advantage of Java streams API. Grouping the values by name and getting the highest grade:

Map<String, Result> map = newSet.stream()
    .collect(Collectors.toMap(Result::getName, Function.identity(), 
    BinaryOperator.maxBy(Comparator.comparing(Result::getGrade))));

I've tested it using the following:

Result r1 = new Result(1, "Emmanuel", "14");
Result r2 = new Result(2, "Emmanuel", "15");

And the result is:

{Emmanuel=Result{date=2, name='Emmanuel', grade='15'}}