1
0

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 5 years have passed since last update.

ラムダ式の基本

Posted at
1 / 8

ラムダ式の構文

(型 引数名1,型 引数名2,…) ->{
処理1;
処理2;
.
.
.
return 戻り値;
}


public static void main(String[]args){

Runnable runner = () -> {
System.out.println("Hello Lambda!");};
runner.run();
}


public static void main(String[]args){

IntBinaryOperator func = (int a, int b)->{return a-b;};

int a = func.applyAsInt(5,3);
System.out.println(a);
}
}

インターフェースの場合

interface InterfaceTest{
public String method(String name,int n);
}
publicclass Main{
public static void main(String[] args){
InterfaceTest it = (name,n) ->{
return "Hello" + name + n + "!";
};
System.out.println(it.method("Java", 8));
}
}

Stream API

.for Each → forループ文を手短に書いた場合
.filter → 条件式を満たす場合の処理
.sorted → ソート処理を行う
.map → 引数を四則演算する方法


for Eachの例

Integer[]num = {1,2,3,4,5}
Listl = Arrays,asList(num);

l.forEach(System.out.println);

こっちでもおk↓

l.forEach(i->
System.out.println(i));


fillterの例

l.strem().filter(x -> x < 3)
.forEach(i -> System.out.println(i));


sortedの例

l.stream().sorted((x,y) -> y - x)
.forEach(i-> System.out.println(i));

mapの例

l.stream().map(x -> x * 10 - 5)
.forEach(i -> System.out.println(i));

mapをもっとわかりやすく

Listlist = Array.asList(-1,2,0,-3,8);
list.stream().fitter(i -> return i >= 0)
.sorted((i1,i2) -> return i1 - i2)
.map(i -> return "" + i + "")
.forEach(s -> System.out.println(s + "));


1
0
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?