0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Java8]streamを使ってint型の配列を降順ソートする

Last updated at Posted at 2020-03-04

概要

  • 勉強中にひっかかったところのメモ
  • Integer型だと使えたけど、int型の降順だと、Comparatorが使えなかった。
  • 結論は、boxedを使えばできるようだった。

サンプルプログラム

  • 「int型配列を使って、次の数字を降順に並び替えて出力しなさい」みたいな問題
import java.util.Arrays;
import java.util.Comparator;

public class Main {
    public static void main(String[] args) throws Exception {
        
        // 入力
        int[] numArray = {4, 3, 2, 5, 6, 7, 3, 2, 1, 9, 7, 8, 10, 6, 4, 3, 5, 8, 9};

        Arrays.stream(numArray)
                .boxed()
                .sorted(Comparator.reverseOrder())
                .forEach(i -> System.out.print(i + " "));
    }
}

出力結果

10 9 9 8 8 7 7 6 6 5 5 4 4 3 3 3 2 2 1 

filter や distinct を組み合わせれば、絞り込みや重複の削除もできる

import java.util.Arrays;
import java.util.Comparator;

public class Main {
    public static void main(String[] args) throws Exception {
        
        // 入力
        int[] numArray = {4, 3, 2, 5, 6, 7, 3, 2, 1, 9, 7, 8, 10, 6, 4, 3, 5, 8, 9};

        Arrays.stream(numArray)
                .boxed()
                .distinct()
                .filter(x -> x >= 5)
                .sorted(Comparator.reverseOrder())
                .forEach(i -> System.out.print(i + " "));
    }
}

出力結果

10 9 8 7 6 5 

配列自体を書きかえるならこんな感じみたいです

import java.util.Arrays;
import java.util.Comparator;

public class Main {
    public static void main(String[] args) throws Exception {
        
        // 入力
        int[] numArray = {4, 3, 2, 5, 6, 7, 3, 2, 1, 9, 7, 8, 10, 6, 4, 3, 5, 8, 9};
                
        numArray = Arrays.stream(numArray)
            .boxed()
            .distinct()
            .filter(x -> x >= 5)
            .sorted(Comparator.reverseOrder())
            .mapToInt(Integer::intValue)
            .toArray();
        System.out.println(Arrays.toString(numArray));
    }
}

出力結果

[10, 9, 8, 7, 6, 5]

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?