简体   繁体   中英

How to sort an array of strings alphabetically by second word in Java

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!

You need to provide a Comparator that will look at the String s 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 String s 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]);
    }
}

Use TreeMap , the entries will be sorted by key.

Eg:

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);
}

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 .

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);
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM