2016-09-04 3 views
0

У меня есть список целых чисел, которые хранятся в другом arraylist.сортировка в массиве arraylist

List<List<Integer>> h = new ArrayList<List<Integer>>(); 
ArrayList<Integer> temp = new ArrayList<Integer>(); 
temp.add(x1); 
temp.add(x2); 
temp.add(y); 
h.add(temp); 

Я хотел бы отсортировать его по первому номеру этого массива.

input 
(2 4 3) 
(1 3 2) 
(3 4 5) 

expected output 
(1 3 2) 
(2 4 3) 
(3 4 5) 

Я попытался с помощью Collections.sort, но это, кажется, не работает. Есть ли какой-либо другой метод, который я могу попробовать отсортировать?

+0

Аналогично [как-к-рода-ан-ArrayList-содержащий-строку-массивы] (https://stackoverflow.com/questions/39059094/how-to-sort-an-arraylist- что-содержит-струнные-массивы). – pmcevoy12

ответ

1

Вы хотите, чтобы пользовательский компаратор сравнивал списки списков целых чисел.

public class ListComparator implements Comparator<List<Integer>> { 
    @Override 
    public int compare(List<Integer> list1, List<Integer> list2) { 
     int value1 = list1.get(0); 
     int value2 = list2.get(0); 
     return Integer.compare(value1, value2); 
    } 
} 

Затем вы передаете его в качестве второго аргумента для сортировки.

Collections.sort(demoList, new ListComparator()); 

EDIT - это версия, которая обрабатывает пустые и пустые списки в отсортированном списке.

public class ListComparator implements Comparator<List<Integer>> { 
    @Override 
    public int compare(List<Integer> list1, List<Integer> list2) { 
     int result = 0; 
     if (list1 == null) { 
      // define null as equal to null and less than everything else 
      result = (list2 == null) ? 0 : -1; 
     } 
     else if (list1.isEmpty()) { 
      // define empty as greater than null, equal to empty, and less than non-empty 
      result = (list2 == null) ? 1 : (list2.isEmpty() ? 0 : -1); 
     } 
     else if (list2 == null || list2.isEmpty()) { 
      // define non-empty (list1) as greater than null or empty 
      result = 1; 
     } 
     else { 
      // both are non-empty so compare the first values from each 
      int value1 = list1.get(0); 
      int value2 = list2.get(0); 
      result = Integer.compare(value1, value2); 
     } 
     return result; 
    } 
} 
Смежные вопросы