Compare two strings in ArrayList to find each person highest grade

I’m trying to implement here an ArrayList with the highest grade each person has. I need to read the text file and sort out lines with the person name and grade from there.

After sorting namesWithGrades the output looks like this:

[David Doe 3, Carol White 3, Bob Brown 4, Bob Brown 4, Alice Smith 4, David Doe 4, Alice Smith 5, Bob Brown 5]

The desired output should look like this in any order:

[Carol White 3, David Doe 4, Alice Smith 5, Bob Brown 5]

My question is that, how am I able to compare names and grades in namesWithGrade ArrayList to get the desired result for result ArrayList?

My main code so far:

public List<String> getFullNamesWithHighestGrade() {
        readLines();
        List<String> namesWithGrade = new ArrayList<>();
        List<String> result = new ArrayList<>();
        for(String person: dataOrig){
            String[] data = person.split("\|");
            namesWithGrade.add(data[0] + " " + data[1] + " " + data[3]);
        }
        namesWithGrade.sort(Comparator.comparing(s -> s.split(" ")[2]));
        System.out.println(namesWithGrade);
        
        return result;
    }

Reading data from grades.txt file:

private static final String FILE_PATH = "src/ex1/grades.txt";
    public List<String> dataOrig;

    private List<String> readLines() {
        try {
            dataOrig = Files.readAllLines(Paths.get(FILE_PATH));
            return dataOrig;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

grades.txt file:

Alice|Smith|math|5
Bob|Brown|english|4
David|Doe|math|3
Bob|Brown|math|4
Bob|Brown|chemistry|5
Alice|Smith|english|4
Carol|White|chemistry|3
David|Doe|chemistry|4

Answer

Create a HashMap. Here’s an example of how it might be:

HashMap<String, Integer> results = new HashMap<String, Integer>();

for(String person: dataOrig) {
    String[] data = person.split(“\|”);
    String currentName = data[0] + “ “ + data[1]; //get the name of the current line
    int currentGrade = Integer.parseInt(data[3]); //get the grade of the current line 
    if(results.containsKey(currentName)) { //if the name is in the HashMap with a grade
        if(currentGrade > results.get(currentName)) { //if the current grade is greater than the one that is already in the HashMap, replace it.
            results.put(currentName, currentGrade);
        }
    }
    else //if the name hasn’t been added to the HashMap yet, put it in.
        results.put(currentName, currentGrade);
}

The HashMap should now contain the names with the correct highest grade. No need to use 2 ArrayLists. You can print out the results with this loop. To sort the HashMap by values, check out this link: https://www.google.com/amp/s/www.geeksforgeeks.org/sorting-a-hashmap-according-to-values/amp/

for(Map.Entry<String, Integer> entry : results.entrySet()) {
    System.out.println(entry.getKey() + “ “ + entry.getValue());
}