函数式接口 @FunctionalInterface
package com.demo;
import java.util.Arrays;
import java.util.Comparator;
public class Demo {
public static void main(String[] args) {
String[] array = new String[]{"pig", "cat", "dog"};
Arrays.sort(array, new Comparator<String>(){
@Override
public int compare(String s1, String s2) {
return s1.compareTo(s2);
}
});
System.out.println(Arrays.toString(array));
// [cat, dog, pig]
}
}
Lambda表达式
package com.demo;
import java.util.Arrays;
public class Demo {
public static void main(String[] args) {
String[] array = new String[]{"pig", "cat", "dog"};
Arrays.sort(array, (s1, s2) -> {
return s1.compareTo(s2);
});
System.out.println(Arrays.toString(array));
// [cat, dog, pig]
}
}
引用静态方法
package com.demo;
import java.util.Arrays;
public class Demo {
public static void main(String[] args) {
String[] array = new String[]{"pig", "cat", "dog"};
Arrays.sort(array, Demo::compareTo);
System.out.println(Arrays.toString(array));
// [cat, dog, pig]
}
public static int compareTo(String s1, String s2){
return s1.compareTo(s2);
}
}
引用实例方法
// public int compareTo(String anotherString)
// 相当于:
// public static int compareTo(String this, String anotherString)
Arrays.sort(array, String::compareTo);
引用构造方法
class Person {
private String name;
public Person(String name) {
this.name = name;
}
}
package com.demo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Demo {
public static void main(String[] args) {
List<String> names = Arrays.asList("Tom", "Jack", "Steve");
List<Person> persons = new ArrayList<>();
for (String name : names) {
persons.add(new Person(name));
}
}
}
简写
package com.demo;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Demo {
public static void main(String[] args) {
List<String> names = Arrays.asList("Tom", "Jack", "Steve");
List<Person> persons = names.stream()
.map(Person::new)
.collect(Collectors.toList());
}
}
创建Stream
String[] pets = new String[]{"pig", "dog", "cat"};
Stream<String> stream = Arrays.stream(pets);
Stream<String> stream = Stream.of("pig", "dog", "cat");
Stream<String> stream = Arrays.asList("pig", "dog", "cat").stream();
// 映射
Stream<Integer> stream = Stream.of(1, 2, 3);
stream.map(x -> x * x).forEach(System.out::println);
// 1 4 9
// 过滤,留下偶数
Stream<Integer> stream = Stream.of(1, 2, 3);
stream.filter(x -> x % 2 == 0).forEach(System.out::println);
// 2
// 聚合
Stream<Integer> stream = Stream.of(1, 2, 3);
int ret = stream.reduce(0, (sum, x) -> sum + x);
System.out.println(ret);
// 2
Stream提供的常用操作有:
转换操作:map(),filter(),sorted(),distinct();
合并操作:concat(),flatMap();
并行处理:parallel();
聚合操作:reduce(),collect(),count(),max(),min(),sum(),average();
其他操作:allMatch(), anyMatch(), forEach()。