0

I have a list of integer that is stored into another 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);

i would like to sort it according to the first number of that array.

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

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

I have tried using collections.sort but it seems to be not working. Are there any other method i can try sorting it?

Jinny
  • 83
  • 4
  • Similar to [how-to-sort-an-arraylist-that-contains-string-arrays](https://stackoverflow.com/questions/39059094/how-to-sort-an-arraylist-that-contains-string-arrays). – pamcevoy Sep 04 '16 at 22:11

1 Answers1

1

You want a custom comparator to compare lists of lists of integers.

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);
    }
}

Then you pass it in as the second argument to sort.

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

EDIT - here is a version that handles null and empty lists in the list being sorted.

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;
    }
}
pamcevoy
  • 1,136
  • 11
  • 15