LoginSignup
0
1

More than 3 years have passed since last update.

java comparator を使ったソート

Last updated at Posted at 2020-06-23
  • comparator を使うと便利にソートできます.

コード (昇順ソート)


import java.util.*;

class Solution {

    public static void main(String[] args) {
        sort1();
        sort2();
    }

    public static void sort1 () {
        List<Integer> list1 = Arrays.asList(3,2,8,4);
        System.out.println("sort前: "+list1);
        Comparator<Integer> comparator = new Comparator<Integer>() {
            public int compare(Integer int1, Integer int2) {
                return (int1.compareTo(int2));
            }
        };
        Collections.sort(list1, comparator);
        System.out.println("comparator(インスタンス化する), sort 後: "+list1);
    }

    public static void sort2(){
        List<Integer> list1 = Arrays.asList(3,2,8,4);
        System.out.println("sort前: "+list1);
        Collections.sort(list1, (a, b) -> Integer.compare(a, b));
        System.out.println("ラムダ式comparator, sort 後: "+list1);
    }
}

出力結果

sort前: [3, 2, 8, 4]
comparator(インスタンス化する), sort 後: [2, 3, 4, 8]
sort前: [3, 2, 8, 4]
ラムダ式comparator, sort 後: [2, 3, 4, 8]

0
1
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
1