Reputation: 611
I have many lists, every list contains 4 elements all string.
Now I have a Set<List>
which stores all the above lists.
I want to sort the set on the basis of a field in list.
eg. list1=["x","2"], list2=["a","5"], list3=["g","1"]
and set.add(list1), set.add(list2), set.add(list3)
.
Now I want to sort that set on the basis of 2nd fields in list.
Upvotes: 1
Views: 688
Reputation: 13858
So you have like this:
List<String> list1 = Arrays.asList("x", "2");
List<String> list2 = Arrays.asList("a", "5");
List<String> list3 = Arrays.asList("g", "1");
And one super-list
Set<List<String>> set = new HashSet<List<String>>();
set.add(list1);
set.add(list2);
set.add(list3);
And you need a sorted List over the second String:
List<List<String>> list = new ArrayList<List<String>>(set);
Collections.sort(list, new Comparator<List<String>>() {
@Override
public int compare(List<String> o1, List<String> o2) {
//Index 1 = second element
return o1.get(1).compareTo(o2.get(1));
}
});
Full Example
List list1 = Arrays.asList("x", "2"); List list2 = Arrays.asList("a", "5"); List list3 = Arrays.asList("g", "1");
Set<List<String>> set = new HashSet<List<String>>();
set.add(list1);
set.add(list2);
set.add(list3);
List<List<String>> list = new ArrayList<List<String>>(set);
Collections.sort(list, new Comparator<List<String>>() {
@Override
public int compare(List<String> o1, List<String> o2) {
//Index 1 = second element
return o1.get(1).compareTo(o2.get(1));
}
});
for(List<String> li : list) {
System.out.println(li);
}
Creates this output / sorting:
[g, 1]
[x, 2]
[a, 5]
Upvotes: 1