sort an arraylist of arraylist of integers

后端 未结 3 1201
庸人自扰
庸人自扰 2021-01-06 04:57

I am looking to sort an arraylist of arraylist of integers and I require help?

I was informed that I need to implement comparator or comparable and then use the coll

3条回答
  •  时光取名叫无心
    2021-01-06 05:27

    No error check for null lists, but here it is.

    List> list = Arrays.asList(Arrays.asList(10, 5, 4), 
            Arrays.asList(3, 2, 1), Arrays.asList(7, 8, 6));
    for (List l : list) {
        Collections.sort(l);
    }
    Collections.sort(list, new Comparator>() {
        public int compare(List o1, List o2) {
            return o1.get(0).compareTo(o2.get(0));
        }
    });
    System.out.println(list);
    

    With Java 8 it gets even more concise:

    List> list = Arrays.asList(Arrays.asList(10, 5, 4),
                    Arrays.asList(3, 2, 1), Arrays.asList(7, 8, 6));
    list.forEach(Collections::sort);
    Collections.sort(list, (l1, l2) -> l1.get(0).compareTo(l2.get(0)));
    System.out.println(list);
    

提交回复
热议问题