filter方法用于通过设置条件过滤出满足条件的元素。以下代码片段使用filter方法过滤出空字符串。
List list = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List filtered = list.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
sorted方法用于对流进行排序。以下代码片段使用sorted方法对集合中的数字进行排序
List numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
numbers.stream().sorted().forEach(System.out::println);
注意:
Streamsorted(); //自然排序
空参的sorted函数默认调用集合元素的Comparable接口进行对比,如果是自定义类需要实现Comparable接口,重写compareTo(Object obj)
Streamsorted(Comparator super T> comparator); //定制排序
带参的sorted函数需要传入Comparator的对象,重写compare(Object o1,object o2)方法
map方法用于映射每个元素到对应的结果。以下代码片段使用map获取人的姓名
List names = persons.stream().map(Person::getName).collect(Collectors.toList());
distinct 方法用于去掉重复数据。以下代码片段使用filter方法过滤出空字符串并去重
List list = Arrays.asList("abc", "", "bc", "efg", "abc","", "jkl");
List filtered = list.stream().filter(string -> !string.isEmpty()).distinct().collect(Collectors.toList());
count 方法用于统计集合内对象的数量,以下代码片段使用filter方法过滤出空字符串并计数
List list = Arrays.asList("abc", "", "bc", "efg", "abc","", "jkl");
long count = list.stream().filter(string -> !string.isEmpty()).count();
Collectors类实现了很多归约操作,例如将流转换成集合和聚合元素。
Collectors可用于返回列表或字符串:
Liststrings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
System.out.println("原列表筛选后列表: " + filtered);
String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", "));
System.out.println("合并字符串: " + mergedString);
底层代码:
1. public staticCollector >>
groupingBy(Function super T, ? extends K> classifier) {
return groupingBy(classifier, toList());
}
2. public static
Collector> groupingBy(Function super T, ? extends K> classifier,
Collector super T, A, D> downstream) {
return groupingBy(classifier, HashMap::new, downstream);
}
3. public staticextends Map>
CollectorgroupingBy(Function super T, ? extends K> classifier,
SuppliermapFactory,
Collector super T, A, D> downstream) {
Supplier downstreamSupplier = downstream.supplier();
BiConsumersuper T> downstreamAccumulator = downstream.accumulator();
BiConsumer
K key = Objects.requireNonNull(classifier.apply(t), "element cannot be mapped to a null key");
A container = m.computeIfAbsent(key, k -> downstreamSupplier.get());
downstreamAccumulator.accept(container, t);
};
BinaryOperator
@SuppressWarnings("unchecked")
Supplier
if (downstream.characteristics().contains(Collector.Characteristics.IDENTITY_FINISH)) {
return new CollectorImpl<>(mangledFactory, accumulator, merger, CH_ID);
}
else {
@SuppressWarnings("unchecked")
Function downstreamFinisher = (Function) downstream.finisher();
Function, M> finisher = intermediate -> {
intermediate.replaceAll((k, v) -> downstreamFinisher.apply(v));
@SuppressWarnings("unchecked")
M castResult = (M) intermediate;
return castResult;
};
return new CollectorImpl<>(mangledFactory, accumulator, merger, finisher, CH_NOID);
}
}
Map> collect = list.stream().collect(Collectors.groupingBy(Person::getName));
Map> collect = list.stream()
.collect(Collectors.groupingBy(Person::getName, LinkedHashMap::new,Collectors.toList()));
分组的字段按照TreeMap的规则进行排序放入Map,底层是TreeMap
Map> collect = list.stream()
.collect(Collectors.groupingBy(Person::getAge, TreeMap::new, Collectors.toList())); //TreeMap默认以升序排序
Map>> planOrgMap = new HashMap<>();
planOrgList.stream().collect(Collectors.groupingBy(PlanOrg::getType)).
forEach((type, list2) -> {
Map> planOrgMap_tmp = list2.stream().collect(
Collectors.groupingBy(PlanOrg::getPlanOrgId)
);
planOrgMap.put(type, planOrgMap_tmp);
});
long count = Persons.stream().filter(a -> a.getAge() > 5).count();
System.out.println("age > 5的人数 = " + count);
int sumAge = persons.stream().mapToInt(Person::getAge).sum();
int maxAge = persons.stream().mapToInt(Person::getAge).max().getAsInt();
int minAge = persons.stream().mapToInt(Person::getAge).min().getAsInt();
double avgAge = persons.stream().mapToInt(Person::getAge).average().getAsDouble();
流用一次就不能用第二次,可以一次性获取一个流的所有统计信息。
IntSummaryStatistics statistics = persons.stream().mapToInt(Person::getAge).summaryStatistics();
System.out.println("count = " + statistics.getCount());
System.out.println("sumAge = " + statistics.getSum());
System.out.println("maxAge = " + statistics.getMax());
System.out.println("minAge = " + statistics.getMin());
System.out.println("avgAge = " + statistics.getAverage());