Radioactive Coffe Radioactive Coffe - 1 month ago 7
Java Question

Sort a String array by second word

I have the following data

1. John Smith
2. Tom Cruise
3. Chuck Norris
4. Bill Gates
5. Steve Jobs


As you can see, the data is in specific format,
[ID]. [Firstname] [Lastname]
. Is there a way to sort this array by
Firstname
?

Output should look something like this:

4. Bill Gates
3. Chuck Norris
1. John Smith
5. Steve Jobs
2. Tom Cruise

Answer

You can use lambda to pass your own comparison criteria.

String[] names = {"1. John Smith", "2. Tom Cruise", "3. Chuck Norris", "4. Bill Gates", "5. Steve Jobs"};

ArrayList<String> namesList = new ArrayList<>();
for(int i=0; i<names.length; i++) {
    namesList.add(names[i]);
}

Collections.sort(namesList, (name1, name2) -> name1.split(" ")[1].compareTo(name2.split(" ")[1]));

for(String name : namesList) {
    System.out.println(name);
}

Output:

4. Bill Gates
3. Chuck Norris
1. John Smith
5. Steve Jobs
2. Tom Cruise
Comments