I have a project where the main functionality is to read a .txt file into a String array and sort it by specific String value in each line. My .txt file is a list of employees with their name, salary ,and experience. Below is my examplary list:
- Name: Thomas Green | Gross salary: 10 000 | Experience: 30 months
- Name: Anna Lang | Gross salary: 6 000 | Experience: 12 months
- Name: Micheal Holse | Gross salary: 8 000 | Experience: 27 months
Now what I want is to sort this list through first name, salary value or experience value, after using a Scanner to change this list into an array. I have read about Comparator, but couldn't find a right example. As you see, what this program has to do is to skip "Name:" value and sort it alphabetically by first name. Or skip other Strings and sort a list by the lowest salary value. The same for experience it should sort by a number of months from the lowest to the highest.
Here is what I could do until now:
import java.io.File;
import java.io.IOException;
import java.util.*;
public class SortList {
public static int loadInt() {
Scanner s = new Scanner(System.in);
if(!s.hasNextInt()) {
s.next();
s.nextLine();
return loadInt();
}
return s.nextInt();
}
public static void main (String[] args) throws IOException{
//show the list
String token1 = "";
Scanner inFile1 = new Scanner (new File ("list.txt")).useDelimiter(",\\s*");
List<String> temps = new ArrayList<String>();
while(inFile1.hasNext()) {
token1 = inFile1.next();
temps.add(token1);
}
inFile1.close();
String[] tempsArray = temps.toArray(new String[0]);
for(String s : tempsArray) {
System.out.println(s);
}
//Sort the list
System.out.println("How do you want to sort?" + "\n" + "1. By name" + "\n" + "2. By salary" + "\n" + "3. By experience");
int b;
b = loadInt();
if (b == 1){
ArrayList<String> namesList = new ArrayList<>();
for(int i = 0; i<tempsArray.length; i++){
namesList.add(tempsArray[i]);
}
Collections.sort(namesList, (name1, name5) -> name1.split(" ")[1].compareTo(name5.split(" ")[1]));
for(String name : namesList){
System.out.println(name);
}
}
if (b == 2){
ArrayList<String> salaryList = new ArrayList<>();
for(int i = 0; i<tempsArray.length; i++){
salaryList.add(tempsArray[i]);
}
Collections.sort(salaryList, (salary1, salary2) -> salary1.split(" ")[10].compareTo(salary2.split(" ")[10]));
for(String salary : salaryList){
System.out.println(salary);
}
}
if (b == 3){
ArrayList<String> experienceList = new ArrayList<>();
for(int i = 0; i<tempsArray.length; i++){
experienceList.add(tempsArray[i]);
}
Collections.sort(experienceList, (experience1, experience2) -> experience1.split(" ")[14].compareTo(experience2.split(" ")[14]));
for(String experience : experienceList){
System.out.println(experience);
}
}
}
}
For now my code doesn't sort the list when I enter a integer value. Is the way I'm doing that is correct? I found example of Collection through internet, but it doesn't work for me.