标签:遍历 asList rri 匿名 new tput tar slist thread
import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.function.Supplier; public class LambdaTest { @Test public void test1() { // 用匿名内部类的方式来创建线程 new Thread(new Runnable() { @Override public void run() { System.out.println("用匿名内部类的方式来创建线程!"); } }).start(); // 使用Lambda来创建线程 new Thread(() -> System.out.println("使用Lambda来创建线程!")).start(); Runnable runnable = () -> System.out.println("Lambda语法实现runnable"); new Thread(runnable).start(); List<String> items = new ArrayList<>(); items.add("A"); items.add("B"); items.add("C"); items.add("D"); items.add("E"); //lambda //Output : A,B,C,D,E items.forEach(item->System.out.println(item)); } @Test public void test2(){ // Consumer 一个入参,无返回值 Consumer<String> consumer = s -> System.out.println(s); consumer.accept("Lambda语法Consumer案例!"); Consumer<String> consumer1 = System.out::println; consumer.accept("Lambda语法Consumer案例2!"); // Supplier 无入参,有返回值 Supplier<String> supplier = () -> "Lambda语法Supplier案例!"; String s = supplier.get(); System.out.println(s); //Supplier<Category> categorySupplier = Category::new; //System.out.println(categorySupplier); } @Test public void test3(){ //lambda表达式和函数式接口Predicate List<String> languages = Arrays.asList("Java", "Scala", "C++", "Haskell", "Lisp"); System.out.println("Languages which starts with J :"); //调用自己方法filter filter(languages, (str) -> ((String)str).startsWith("J")); System.out.println("Languages which ends with a "); filter(languages, (str) -> ((String)str).endsWith("a")); System.out.println("Print all languages :"); filter(languages, (str) -> true); System.out.println("Print no language : "); filter(languages, (str) -> false); System.out.println("streamFilter Test : "); testFilter(languages); //map } public static void filter(List<String> names, Predicate condition) { /* names.forEach(s -> { if (condition.test(s)){ System.out.println(s); } });*/ names.stream().filter(condition).forEach(System.out::println); } //lambda表达式中加入Predicate public static void testFilter(List<String> names){ Predicate<String> startsWithJ = (n) -> n.startsWith("J"); Predicate<String> fourLetterLong = (n) -> n.length() == 4; names.stream() .filter(startsWithJ.and(fourLetterLong)) //filter 验证是否符合该条件 and or .. .forEach((n) -> System.out.print("nName, which starts with ‘J‘ and four letter long is : " + n)); } @Test public void mapTest(){ //使用lambda表达式的Map和Reduce示例 List<Integer> costBeforeTax = Arrays.asList(100, 200, 300, 400, 500); //map替换array值并遍历 costBeforeTax.stream().map((cost) -> cost + .12*cost).forEach(System.out::println); //使用lambda表达式的Map示例 map替换值之后 reduce计算list的总和 double bill = costBeforeTax.stream().map((cost) -> cost + .12*cost) .reduce((sum, cost) -> sum + cost).get(); System.out.println("总和:"+bill); } }
标签:遍历 asList rri 匿名 new tput tar slist thread
原文地址:https://www.cnblogs.com/hnzkljq/p/11692172.html