0
0

More than 1 year has passed since last update.

Collection.sortを勉強する

Posted at

デフォルトはacending
acending以外にしたい場合、comparatorを作って渡す
sortは、comparatorのcompare結果が0以下となるように並び替える
昇順にしたければp1-p2、降順にしたければp2-p1

    public static void main(String[] args) {
        List<Integer> li = new ArrayList();
        li.add(1);
        li.add(100);
        li.add(3);
        Comparator c = new Outer().new DecendingComparator();
        Collections.sort(li);
        for(Integer i:li) {
            System.out.println(i);
        }
        System.out.println("----------------------");
        Collections.sort(li, c);
        for(Integer i:li) {
            System.out.println(i);
        }
    }
    class DecendingComparator implements Comparator<Integer> {
        @Override
        public int compare(Integer i,Integer j) {
            return j - i;
        }
    }
1
3
100
----------------------
100
3
1
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0