流的构成
当我们使用一个流的时候,通常包括三个基本步骤:
获取一个数据源(source)→ 数据转换→执行操作获取想要的结果。
流的操作
-
Intermediate(可多次):
map (mapToInt, flatMap 等)、 filter、 distinct、 sorted、 peek、 limit、 skip、 parallel、 sequential、 unordered -
Terminal(仅一次):
forEach、 forEachOrdered、 toArray、 reduce、 collect、 min、 max、 count、 anyMatch、 allMatch、 noneMatch、 findFirst、 findAny、 iterator -
Short-circuiting(输入无限大 Stream 有限时间内完成操):
anyMatch、 allMatch、 noneMatch、 findFirst、 findAny、 limit
map/flatMap
它的作用就是把 input Stream 的每一个元素,映射成 output Stream 的另外一个元素。
// 转换大写
List<String> output = wordList.stream().
map(String::toUpperCase).
collect(Collectors.toList());
// list 打平
List<List<String>> lists = new ArrayList<>();
List<String> flatMapList = lists.stream()
.flatMap(pList -> pList.stream())
.collect(Collectors.toList());
filter
filter 对原始 Stream 进行某项测试,通过测试的元素被留下来生成一个新 Stream。
// 留下偶数
Integer[] sixNums = {1, 2, 3, 4, 5, 6};
Integer[] evens =
Stream.of(sixNums).filter(n -> n%2 == 0).toArray(Integer[]::new);
forEach
forEach 方法接收一个 Lambda 表达式,然后在 Stream 的每一个元素上执行该表达式。
forEach 是 terminal 操作(具有相似功能的 intermediate 操作 peek 可以达到上述目的)。
// 打印姓名
roster.stream()
.filter(p -> p.getGender() == Person.Sex.MALE)
.forEach(p -> System.out.println(p.getName()));
findFirst
返回 Stream 的第一个元素,或者空。
reduce
这个方法的主要作用是把 Stream 元素组合起来。
它提供一个起始值(种子),然后依照运算规则(BinaryOperator),和前面 Stream 的第一个、第二个、第 n 个元素组合。
// 字符串连接,concat = "ABCD"
String concat = Stream.of("A", "B", "C", "D").reduce("", String::concat);
// 字符串连接,concat = "->ABCD"
String concat = Stream.of("A", "B", "C", "D").reduce("->", String::concat);
// 求最小值,minValue = -3.0
double minValue = Stream.of(-1.5, 1.0, -3.0, -2.0).reduce(Double.MAX_VALUE, Double::min);
limit/skip
limit 返回 Stream 的前面 n 个元素;skip 则是扔掉前 n 个元素。
sorted
List<Person> personList2 = persons.stream().limit(2).sorted((p1, p2) -> p1.getName().compareTo(p2.getName())).collect(Collectors.toList());
min/max/distinct
Match
boolean isAllAdult = persons.stream().
allMatch(p -> p.getAge() > 18);
groupingBy/partitioningBy
用 Collectors 来进行 reduction 操作
// 按照年龄归组
Map<Integer, List<Person>> personGroups = Stream.generate(new PersonSupplier()).
limit(100).
collect(Collectors.groupingBy(Person::getAge));
// 按照未成年人和成年人归组
Map<Boolean, List<Person>> children = Stream.generate(new PersonSupplier()).
limit(100).
collect(Collectors.partitioningBy(p -> p.getAge() < 18));
Collectors.toMap
List<Hosting> list = new ArrayList<>();
list.add(new Hosting(1, "liquidweb.com", 80000));
list.add(new Hosting(2, "linode.com", 90000));
list.add(new Hosting(3, "digitalocean.com", 120000));
list.add(new Hosting(4, "aws.amazon.com", 200000));
list.add(new Hosting(5, "mkyong.com", 1));
list.add(new Hosting(6, "linode.com", 70000));
// key = id, value - websites
Map<Integer, String> result1 = list.stream().collect(Collectors.toMap(Hosting::getId, Hosting::getName));
// key = id, value = name
Map<Integer, String> result3 = list.stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getName()));
// key = name, value - websites , but the key 'linode' is duplicated!?
// (oldValue, newValue) -> oldValue,
// if same key, take the old key
Map<String, Long> result1 = list.stream().collect(
Collectors.toMap(Hosting::getName, Hosting::getWebsites, (oldValue, newValue) -> oldValue)
);
附录
class PersonSupplier implements Supplier<Person> {
private int index = 0;
private Random random = new Random();
@Override
public Person get() {
return new Person(index++, "StormTestUser" + index, random.nextInt(100));
}
}
class Person {
public int no;
private String name;
public Person (int no, String name) {
this.no = no;
this.name = name;
}
public String getName() {
System.out.println(name);
return name;
}
}
网友评论