ラムダ式
関数を生み出し、即時利用
public class Main {
public static void main(String[] args) {
double b = 3.14;
IntToDoubleFunction func = x -> {
x = 3;
return x * x * b;
};
Function <String, Integer> func1 = (String s) ->{
return s.length();};
int num = func1.apply("ABCD");
System.out.println("ABCDは" + num + "文字です。");
}
}
並び替え
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main6 {
public static void main(String[] args) {
List<Account> list = new ArrayList<>();
list.add(new Account(800,"Saving"));
list.add(new Account(600,"Check"));
list.sort((a, b) -> (a.balanceX - b.balanceX));
list.forEach(account -> System.out.println(account.balanceX + " " + account.accountNo));
}
}
public class Account {
int balanceX;
String accountNo;
Account(int balanceX, String accountNo){
this.balanceX = balanceX;
this.accountNo = accountNo;
}
}
StreamAPI
リストとして取り出す
import java.util.List;
public class Main5 {
public static void main(String[] args) {
List<String> names = List.of("Smith", "Mike", "Keisuke", "Chen");
names.stream().filter(n -> n.length() <= 5).map(n -> n + "さん").forEach(System.out::println);
}
}
条件に合うデータだけを抽出
import java.util.ArrayList;
public class Main7 {
public static void main(String[] args) {
ArrayList<Human> list = new ArrayList<>();
list.add(new Human("Alice", 100));
list.add(new Human("Keisuke", 300));
list.add(new Human("Mark", 400));
list.add(new Human("Sara", 50));
boolean flg = false;
flg = list.stream().anyMatch(h -> h.getHp()>100);
System.out.println(flg);
}
}
参考資料
スッキリわかるJava入門 実践編 第3版 (スッキリわかる入門シリーズ)