Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

java comparator を使ったソート

  • 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]

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away