2
4

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.

Java ラムダ式の使いどころ

Posted at

#概要
Java8からラムダ式が導入された。
本ページは、Javaのラムダ式の使いどころについてのメモページ。
ラムダ式は、StreamAPIと組み合わせて使用すると、使い勝手が良い。

##リストから一定の条件で値を取り出し
###ラムダ式、StreamAPIの使用なし

List<Integer> list = Arrays.asList(2, 9, 5, 7, 4);

for (Integer i : list) {
    if (i >= 5) {
        System.out.println(i);
    }
}

###ラムダ式、StreamAPIを使用あり

List<Integer> list = Arrays.asList(2, 9, 5, 7, 4);

list.stream()
        .filter(i -> i >= 5)
        .forEach(System.out::println);

ラムダ式、StreamAPIを使用したほうがスッキリと可読性良く記載ができる。
以下、ラムダ式、StreamAPIを使用した例を列挙。

##辞書順ソート

List<String> list = Arrays.asList("b", "c", "a", "c", "b");

list.stream()
        .sorted()
        .forEach(System.out::println);

##逆辞書順ソート

List<String> list = Arrays.asList("b", "c", "a", "c", "b");

list.stream()
        .sorted((s1, s2) -> s2.compareTo(s1))
        .forEach(System.out::println);

##重複削除

List<String> list = Arrays.asList("b", "c", "a", "c", "b");

list.stream()
        .distinct()
        .forEach(System.out::println);

##5以上の値の個数をカウント

List<Integer> list = Arrays.asList(2, 9, 5, 7, 4);

long count = list.stream()
        .filter(i -> i >= 5)
        .count();

System.out.println(count);

##5以上の値を合算

List<Integer> list = Arrays.asList(2, 9, 5, 7, 4);

int sum = list.stream()
        .filter(i -> i >= 5)
        .mapToInt(i -> i)
        .sum();

System.out.println(sum);

##1~10の値をマルチスレッドで出力

IntStream.range(0, 10)
        .parallel()
        .forEach(System.out::println);
2
4
1

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
2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?