重要接口
- Predicate 断言接口
对应的lambda 一个参数,返回结果是boolean
(a) -> { return true|false; } - Function 函数接口
对应的lambda 一个参数,一个返回结果,参数和返回结果的类型可以不一样 - BiPredicate 双参数断言
对应的lambda 两个参数,返回结果是boolean
(a, b) -> { return true|false; } - BiFunction 双参数函数接口
两个参数,一个结果
(a, b) -> { 根据ab返回一个结果} - Consumer 消费接口
一个参数 没有结果
(a) -> { 不需要return } - BiConsumer 双参数消费接口
两个参数,没有结果 - Supplier 生产者接口
没有参数,返回一个结果
() -> {return 结果}
Stream api
1. filter
进行过滤的,lambda返回true会留下,lambda返回为false的过滤掉
2. map
映射的, lambda把原有的元素转换为另一个元素, 不会改变个数
3. flatMap
扁平化映射
// 字符串数组 变为 流
List<String> list3 = list.stream().flatMap(strings -> Arrays.stream(strings)).collect(Collectors.toList());
4. forEach
遍历流,接收一个Consumer
list3.stream().forEach( (a) -> {
System.out.println(a);
} );
5. map的流遍历
接收一个BiConsumer
Map<String, String> map = new HashMap<>();
map.put("a", "张");
map.put("b", "李");
map.forEach( (key, value) -> {
System.out.println("key:" +key + " value:" + value);
} );
7. 其它常见api
求个数
System.out.println(list3.stream().count());
去除重复
System.out.println(list3.stream().distinct().collect(toList()));
获取最大最小值
// 返回的是Optional 类型,怕集合为空时,没有合法的最大值
List<String> list4 = Arrays.asList("zhang", "li", "zhao", "wang");
System.out.println(list4.stream().max((a, b) -> a.compareTo(b)));
System.out.println(list4.stream().min((a, b) -> a.compareTo(b)));
如果是数字流,除了最大最小值外,还有平均值,和
System.out.println(IntStream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).max());
System.out.println(IntStream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).min());
System.out.println(IntStream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).average());
System.out.println(IntStream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).sum());
8. 分组
List<Student> students = Arrays.asList(
new Student("zhang", "男", "西安"),
new Student("li", "男", "西安"),
new Student("wang", "女", "北京"),
new Student("zhao", "女", "上海"),
new Student("zhou", "男", "北京")
);
// 按性别分组
Map<String, List<Student>> map3 = students.stream().collect(Collectors.groupingBy((s) -> s.getSex() ));
System.out.println(map3);
// 按城市分组
Map<String, List<Student>> map4 = students.stream().collect(Collectors.groupingBy((s) -> s.getCity()));
System.out.println(map4);
Stream api中有一个重要思想:
Pipeline 流水线思想:把流中的数据一个接一个进行处理。每个数据会经过后续的filter, map等方法依次调用。
在整个执行过程中,lambda表达式是懒惰的,不执行终结方法的话,不会触发lambda的执行。
终结方法: collect, sum, max, min …
运算过程中不会改变原始集合,收集器会生成新的集合对象
9. 流的生成
-
用集合生成
List.stream() -
根据数字
IntStream.of(1,2,3,4); -
把数组变成流
Arrays.stream(数组); -
把文件中的每一行读取出来作为流元素
Files.lines(Paths.get("1.txt")).forEach( s -> System.out.println(s) );
- 使用生产者接口
Stream.generate(生产者接口)
生成5个随机数
Random r = new Random();
Stream.generate( () -> r.nextInt(100) ).limit(5).forEach( x->System.out.println(x));
10. 方法引用(了解)
对lambda表达式的扩展
第一种: 对象::方法名
例子: System.out::println
第二种: 类名::静态方法名
class ABC {
public static boolean aaa(Integer x ) {
// 代码多
return x % 2 == 0;
}
}
可以使用: ABC::aaa
第三种: 类名::new
可以取代 Supplier接口的lambda
例如 () -> new Student()
可以替换为: Student::new
##案例
public class HeroTest1 {
public static void main(String[] args) {
System.out.println(System.getProperty(“user.dir”));
// 将文件内容读取并转化list对象
List list = null;
try (Stream lines = Files.lines(Paths.get(“heroes.txt”))) {
list = lines.map((s) -> {
String[] a = s.split("\t");
return new Hero(
Integer.parseInt(a[0]),
a[1],
a[2],
a[3],
Integer.parseInt(a[4]),
Integer.parseInt(a[5]),
Integer.parseInt(a[6])
);
}).collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
// 1. 找到武将中武力前三的hero对象, 提示流也可以排序
list.stream()
.sorted((h1, h2) -> h2.getPower() - h1.getPower())
.limit(3).forEach(h -> System.out.println(h.getName()));
// 2. 按出生地分组
Map<String, List> group1 = list.stream()
.collect(Collectors.groupingBy((h) -> h.getLoc()));
group1.forEach((k, v) -> {
System.out.println(k + “:” + v.stream()
.map(h -> h.getName())
.collect(Collectors.toList()));
});
// 3. 找出寿命前三的武将
list.stream()
.sorted((h1, h2) -> (h2.getDeath() - h2.getBirth()) - (h1.getDeath() - h1.getBirth()))
.limit(3).forEach(h -> System.out.println(h.getName()));
// 4. 女性寿命最高的
list.stream().
filter(h -> h.getSex().equals(“女”))
.sorted((h1, h2) -> (h2.getDeath() - h2.getBirth()) - (h1.getDeath() - h1.getBirth()))
.limit(3).forEach(h -> System.out.println(h.getName()));
// 5. 找出武力排名前三 100, 99, 97 97 ==> 4个人 “吕布”, “张飞”, “关羽”, “马超”
Set topPowers = list.stream()
.map(h -> h.getPower())
.sorted((p1, p2) -> p2 - p1).limit(3)
.collect(Collectors.toSet());
list.stream()
.filter((h) -> topPowers.contains(h.getPower()))
.forEach((h) -> System.out.println(h.getName()));
// 6. 按各个年龄段分组: 0~20, 2140, 41~60, 60以上
Map<String, List> group2 = list.stream()
.collect(Collectors.groupingBy(h -> ageRange(h.getDeath() - h.getBirth())));
group2.forEach((k, v) -> {
System.out.println(k + “:” + v.stream().map(h -> h.getName())
.collect(Collectors.toList()));
});
// 7. 按武力段分组: >=90, 80~89, 70~79, <70
Map<String, List> group3 = list.stream()
.collect(Collectors.groupingBy(h -> powerRange(h.getPower())));
group3.forEach((k, v) -> {
System.out.println(k + “:” + v.stream()
.map(h -> h.getName()).collect(Collectors.toList()));
});
// 8. 按出生地分组后,统计各组人数
Map<String, Long> group4 = list.stream()
.collect(Collectors.groupingBy((h) -> h.getLoc(), Collectors.counting()));
group4.forEach((k, v) -> {
System.out.println(k + “:” + v);
});
}
public static String powerRange(int power) {
if (power >= 90) {
return "90以上";
} else if (power >= 80 && power <= 89) {
return "80~89";
} else if (power >= 70 && power <= 79) {
return "70~79";
} else {
return "70之下";
}
}
public static String ageRange(int age) {
if (age >= 0 && age <= 20) {
return "0~20";
} else if (age >= 21 && age <= 40) {
return "21~40";
} else if (age >= 41 && age <= 60) {
return "41~60";
} else {
return "60以上";
}
}
}