在函数式接口中使用lambda

1、函数式接口

  • Predicate<T>
boolean test (T t)

Checks a condition and returns a boolean value as result

In filter() method in java.util.stream.Stream which is used to remove elements in the stream that don’t match the given condition (i.e., predicate) as argument.

  • Consumer<T>
void accept(T t)

Operation that takes an argument but returns nothing

In forEach() method in collections and in java.util.stream.Stream; this method is used for traversing all the elements in the collection or stream.

  • Function<T,R>
R apply(T t)

Functions that take an argument and return a result

In map() method in java.util.stream.Stream to transform or operate on the passed value and return a result.

  • Supplier<T>
T get()

Operation that returns a value to the caller (the returned value could be same or different values) In generate() method in java.util.stream.Stream to create an infinite stream of elements.

2.例子

  • 这是包含Stream,function interface,lambda的例子:
Stream.of("hello", "world")
 .filter(str -> str.startsWith("h")) //Predicate Interface
 .forEach(System.out::println);      //Consumer Interface
  • Predicate的例子 
Listing 5-1. PredicateTest.java
import java.util.function.Predicate;

public class PredicateTest {
     public static void main(String []args) {
         Predicate<String> nullCheck = arg -> arg != null;  // return true or false;
         Predicate<String> emptyCheck = arg -> arg.length() > 0; // return true or false;
         Predicate<String> nullAndEmptyCheck = nullCheck.and(emptyCheck); //return true or false
         String helloStr = "hello";
         System.out.println(nullAndEmptyCheck.test(helloStr)); //Predicate interface
         String nullStr = null;
         System.out.println(nullAndEmptyCheck.test(nullStr)); //Predicate interface
     }
}

This program prints:
true
false
  •  Predicate和Consumer
Listing 5-2. RemoveIfMethod.java
import java.util.List;
import java.util.ArrayList;
public class RemoveIfMethod {
     public static void main(String []args) {
         List<String> greeting = new ArrayList<>();
         greeting.add("hello");
         greeting.add("world");
         greeting.removeIf(str -> !str.startsWith("h")); //predicate
         greeting.forEach(System.out::println); //comsumer 
     }
}

print: 
hello
world
  •  Consumer调用accept
Consumer<String> printUpperCase = str -> System.out.println(str.toUpperCase());
printUpperCase.accept("hello");
// prints: HELLO
  • Consumer调用foreach消费 
Listing 5-3. ConsumerUse.java
import java.util.stream.Stream;
import java.util.function.Consumer;
class ConsumerUse {
 public static void main(String []args) {
 Stream<String> strings = Stream.of("hello", "world");
 Consumer<String> printString = System.out::println;
 strings.forEach(printString);
 }
}
This program prints:
hello
world
  •  Function里有map传值
Listing 5-4. FunctionUse.java
import java.util.Arrays;
public class FunctionUse {
 public static void main(String []args) {
 Arrays.stream("4, -9, 16".split(", "))
 .map(Integer::parseInt)
 .map(i -> (i < 0) ? -i : i)
 .forEach(System.out::println);
 }
}


This program prints:
4
9
16
  •  Function调用apply()
Function<String, Integer> strLength = str -> str.length();
System.out.println(strLength.apply("supercalifragilisticexpialidocious"));
// prints: 34
  •  Function和map()
Listing 5-5. CombineFunctions.java
import java.util.Arrays;
import java.util.function.Function;
public class CombineFunctions {
 public static void main(String []args) {
 Function<String, Integer> parseInt = Integer::parseInt;
 Function<Integer, Integer> absInt = Math::abs;
 Function<String, Integer> parseAndAbsInt = parseInt.andThen(absInt);
 Arrays.stream("4, -9, 16".split(", "))
 .map(parseAndAbsInt) //map 只是在stream里传递元素,调用foreach
 .forEach(System.out::println);
 }
}

Hence the code prints the elements as they are, i.e., the 
values 4, -9, and 16 in separate lines.
  •  random::nextBoolean 返回随机的true or false
Listing 5-6. GenerateBooleans.java
import java.util.stream.Stream;
import java.util.Random;
class GenerateBooleans {
 public static void main(String []args) {
 Random random = new Random();
 Stream.generate(random::nextBoolean)//true or false
 .limit(2)
 .forEach(System.out::println);
 }
}
  • Supplier调用get 
Supplier<String> currentDateTime = () -> LocalDateTime.now().toString();
System.out.println(currentDateTime.get()); //Supplier 调用get()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值