Sort List <List <String>> by List Value

I want to sort the list by the values โ€‹โ€‹in the list, it contains three values, the first value is an integer, I convert it to a string, and the other two values โ€‹โ€‹have a string character, I want to sort the list by the first line.

 List<List<String>> detail_View = new ArrayList<List<String>>(); List<String> fieldValues =fieldValues = new ArrayList<String>(); String aString = Integer.toString(ScreenId); fieldValues.add(aString); fieldValues.add(DisplayScreenName); fieldValues.add(TableDisplay); detail_View.add(fieldValues); 

In the above code, I need to sort the list values โ€‹โ€‹using ScreenId

+4
source share
4 answers

Suppose you donโ€™t want to sort an integer (stored as a string) in alphabetical order, you cannot use the default comparator, but you must first convert it to an integer:

 Collections.sort(detail_view, new Comparator<List<String>>(){ int compareTo(List<String> a, List<String> b){ return Integer.valueOf(a.get(0)).compareTo(Integer.valueOf(b.get(0)); } }); 

Can I suggest not using a List for three pieces of data, but your own bean class?

+3
source

You must use two concepts:

  • Collections.sort .
  • Comparator<T> .

I will write your resolved problem as follows:

First you should write your comparator:

 class CustomComparator implements Comparator<List<String>> { @Override public int compare(List<String> o1, List<String> o2) { String firstString_o1 = o1.get(0); String firstString_o2 = o2.get(0); return firstString_o1.compareTo(firstString_o2); } } 

then you use the Collections utility as follows:

 Collections.sort(detail_View, new CustomComparator()); 

after this step, your list:

 List<List<String>> detail_View = new ArrayList<List<String>>(); 

will be sorted by the first index of any nested list.

For more information related to this concept, see:

+3
source

Create a class with three fields; don't move them like List<String> , it's just plain stupid. Matching this class will allow you to sort them as you wish.

+2
source

Java Version 8:

 Collections.sort(fieldValues, Comparator.comparing(e -> e.get(0))); 

This version sorts integers as numbers, not as strings:

 Collections.sort(fieldValues, Comparator.comparing(e -> Integer.valueOf(e.get(0)))); 
+1
source

Source: https://habr.com/ru/post/1396563/


All Articles