5377037 :
I have a data Set like this:
1,JOHN,1934
2,TERENCE,1914
3,JOHN,1964
4,JOHN,1904
5,JOHN,1924
6,JOHN,1954
7,JOHN,1944
8,JOHN,1984
9,JOHN,1974
10,JOHN,1994
Which I've loaded in ArrayList of String[]
from Text file like this:
ArrayList<String[]> records = new ArrayList<>();
String fileLocation = System.getProperty("user.dir");
String dataPath = fileLocation + File.separator + "boys-names.txt";
try {
try (BufferedReader br = new BufferedReader(new FileReader(dataPath))) {
String line;
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
records.add(values);
}
}
} catch (IOException e) {
e.printStackTrace();
}
I wanted to sort data set in increasing year like this:
4,JOHN,1904
2,TERENCE,1914
5,JOHN,1924
1,JOHN,1934
7,JOHN,1944
6,JOHN,1954
3,JOHN,1964
9,JOHN,1974
8,JOHN,1984
10,JOHN,1994
Problem: The built-in sorting method Collections.sort(list);
of ArrayList only works on single type of data. But, in my case I have string with multi-type (string-integer) and sorting should base in Integers. So, is there any way to solve this problem?
Deadpool :
By using java-8 lambda expression, write custom Comparator
that compares Integer
values and use Integer.valueOf
for converting String
to Integer
List<String[]> list = new ArrayList<String[]>();
String[] ar1 = {"1","JOHN","1934"};
String[] ar2 = {"2","TERENCE","1914"};
list.add(ar1);
list.add(ar2);
list.sort((c1,c2)->Integer.valueOf(c1[2]).compareTo(Integer.valueOf(c2[2])));
list.forEach(i->System.out.println(Arrays.toString(i)));
Output
[2, TERENCE, 1914]
[1, JOHN, 1934]