2

I have a little problem with an assignment I'm working on. Basically, I have a file, with Student ID's and their first name in the following format:

17987 Beth

17950 Clark

17936 Aaron

I put the contents of the file in an array, and I need it sorted by the name, not the ID. If I use Arrays.sort(myArray) it will sort it automatically by ID. I'm having a hard time understanding the Comparator, so if you could explain it step by step, it would be easier for me. Thank you!

Community
  • 1
  • 1
V Sebi
  • 4,253
  • 2
  • 15
  • 8

4 Answers4

6

You need to provide a Comparator that will look at the Strings passed to it, and they must have an understanding of what they are looking for. You can do this in a few different ways, but, if you know for certain about the content of the strings, then you can split the Strings based on their space and compare the second value. Alternatively, you could use a regular expression to extract those details.

class SecondWordComparator implements Comparator<String>
{
    @Override
    public int compare(String s1, String s2)
    {
        String[] a1 = s1.split(" ");
        String[] a2 = s2.split(" ");

        // you should ensure that there are actually two elements here
        return a1[1].compareTo(a2[1]);
    }
}
pickypg
  • 22,034
  • 5
  • 72
  • 84
2

Use TreeMap, the entries will be sorted by key.

E.g.:

SortedMap<String, Integer> srtdMap  = new TreeMap<String, Integer>();

srtdMap.put("Beth", 17987);
srtdMap.put("Aaron", 17936 );
srtdMap.put("Clark", 17950);

//key set always returns the same order by name
for(String name : srtdMap.keySet())
{
    int id = srtdMap.get(name);
    System.out.println("name = " + name + ", ID is " + id);
}
amphibient
  • 29,770
  • 54
  • 146
  • 240
  • 1
    You need to flip the order of the TreeMap, as he wants to sort it after the String and not the Integer. – ddmps Mar 04 '13 at 20:56
1

What you can do is run a for loop that would rearrange all the contents of the Array into a final array. Two for loops would be required. The first for loop will go through the Array and the for loop inside the first will look for the first letter and add it to the final Array/Arraylist .

Andre Yonadam
  • 964
  • 1
  • 13
  • 30
1

For a object-oriented approach I would parse the file into a new class, Student, and save those in an Array(List). The class could extend Comparable<Student> There, you can separate the int ID and the String name and have the compareTo(Student student) method return name.compareTo(otherStudent.name). Then you can call the sort method and it will sort it as wanted.

As such:

public class Student implements Comparable<Student> {
    private int id;
    private String name;
    public Student(int id, String name) {
        this.id = id;
        this.name = name;
    }
    @Override
    public int compareTo(Student student) {
        return name.compareTo(student.name);
    }

}
ddmps
  • 4,350
  • 1
  • 19
  • 34