Java—java8函数式
2022年5月30日
Java8函数式
函数式接口
类型
- Consumer :消费型接口
void accept(T t);
Supplier :供给型接口
T get();
Function :函数型接口
R apply(T t);
Predicate : 断言型接口
boolean test(T t);
实践
Consumer
@Test
public void testConsumer() {
say("Hello World!", x -> System.out.println("今天说了句:" + x));
}
// Consumer
public void say(String sentence, Consumer<String> con) {
con.accept(sentence);
}
Supplier
产生随机数
@Test
public void testSupplier() {
List<Integer> list = getNumList(10, () -> (int) (Math.random() * 100));
System.out.println("list = " + list);
}
// Supplier
public List<Integer> getNumList(Integer num, Supplier<Integer> sup) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < num; i++) {
Integer e = sup.get();
list.add(e);
}
return list;
}
Function
字符串小写转大写
@Test
public void testFunction() {
String s = toUpperCase("abcdefgHIjk", (x) -> x.toUpperCase());
System.out.println("s = " + s);
}
// Function
public String toUpperCase(String s, Function<String, String> function) {
String s1 = function.apply(s);
return s1;
}
Predicate
字符串过滤
@Test
public void testPredicate() {
List<String> strings = Arrays.asList("hello", "liwang", "lw", "test", "w");
List<String> list = filterStr(strings, x -> x.length() > 3);
System.out.println("list = " + list);
}
// Predicate
public List<String> filterStr(List<String> list, Predicate<String> pre) {
ArrayList<String> list1 = new ArrayList<>();
for (String s : list) {
if (pre.test(s)) {
list1.add(s);
}
}
return list1;
}
可以看看我的学习——个人博客: 网站:http://www.fuzm.wang/ ————————————————————————— 很多知识都没有掌握,见谅,如有错误请指出,以期进步,感谢!。后续有新的学习,继续补充上来。
