接口
// 在接口中定义默认方法
public default void show3() {
System.out.println("hello")
}
// 静态方法只能由接口名直接调用
// public可以省略
引用
方法引用
// lambda表达省略
usePrintable(i -> System.out.println(i))
// 用方法引用改写
usePrintable(System.out::println)
// 它会自动推导,上述是类::方法
引用对象实例化方法
printString ps = new printString();
usePrintable(ps::printUpper);
引用类的实例方法
usePrintable((x,y,z) -> s.substring(x,y))
// 用改写时第一个参数作为调用者,后面的参数全部传递到方法里
usePrintable(String::substring)
引用构造器
// lambda表达式
useStudentBuilder((name,age) -> new Student(name,age))
// 引用构造方法
useStudentBuilder(Student::new)
函数式接口
@FunctionalInterface
public interface MyInterface {
void build();
}
// 推荐加上注解
常用接口
Supplier 有 T get() 可以获得这个类型的
Consumer 有accept 可以对这个类型进行操作 有andThen()把两个接口组合在一起
Predicate
有test()判断代码块是否符合要求,有negate() 取否
有and(相当于短路与)操作 如return pre.and(pre2).test(s)
有or (相当于短路或)
Function<T,R>
其中R是不同于T的类型,有方法apply()可以操作,从而将T转换为R
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
convert("123", s -> Integer.parseInt(s));
convert("1234", n -> Integer.parseInt(n));
}
private static void convert(String s, Function<String, Integer> fun) {
Integer apply = fun.apply(s);
System.out.println(apply);
}
// 有fun1.andThen(fun2).apply(s)
Stream流
生成流
// Collection类生成流
List<String> list = new ArrayList<>();
Stream<String> stream = list.stream();
Set<String> set = new HashSet<>();
Stream<String> stream1 = set.stream();
// Map类生成流
Map<String, Integer> map = new HashMap<>();
Stream<String> stream2 = map.keySet().stream();
Stream<Integer> stream3 = map.values().stream();
Stream<Map.Entry<String, Integer>> stream4 = map.entrySet().stream();
// 数组生成流
String[] stringArray = {"hello", "world", "java"};
Stream<String> stringArray1 = Stream.of(stringArray);
中间操作
filter – 过滤
list.stream().filter(s -> s.startsWith("张")).filter(s -> s.length() == 3).forEach(System.out::println);
limit() — 取前三个元素
// 取前3个元素读取
list.stream().limit(3).forEach(System.out::println);
skip() — 跳过前3个元素
// 跳过前3个元素
list.stream().skip(3).forEach(System.out::println);
concat() — 合并 distinct() — 去掉重复
// 取前3个元素读取
Stream<String> s1 = list.stream().limit(3);
// 跳过前3个元素
Stream<String> s2 = list.stream().skip(3);
Stream.concat(s1,s2).distinct().forEach(System.out::println);
sort() — 按照规律排序
// 自然排序
list.stream().sorted().forEach(System.out::println);
// 使用比较器排序
list.stream().sorted((ss1, ss2) -> {
int num1 = ss1.length() - ss2.length();
int num2 = num1 == 0 ? ss1.compareTo(ss2) : num1;
return num2;
}).forEach(System.out::println);
map()&mapToInt() — 进行操作
list.stream().map(Integer::parseInt).forEach(System.out::println);
// mapToInt 返回的是intStream,里面有sum()求和方法
int sum = list.stream().mapToInt(Integer::parseInt).sum();
System.out.println(sum);
终极操作
forEach() — 遍历每一个元素
count() — 统计元素个数
收集操作
收集到List listStream.collect(Collectors.toList())
收集到Set setStream.collect(Collectors.toSet())
收集到Map arrayStream.collect(Collectors.toMap()) 其中Map()中的值先写键在写值,写的是lambda表达式(Function)