java8 stream List集合的常用流操作

一、stream基础方法使用

1.filter 过滤

filter方法用于通过设置条件过滤出满足条件的元素。以下代码片段使用filter方法过滤出空字符串。

List list = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List filtered = list.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());

2.sorted 排序

sorted方法用于对流进行排序。以下代码片段使用sorted方法对集合中的数字进行排序

List numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
numbers.stream().sorted().forEach(System.out::println);
注意:
Stream sorted(); //自然排序

空参的sorted函数默认调用集合元素的Comparable接口进行对比,如果是自定义类需要实现Comparable接口,重写compareTo(Object obj)

Stream sorted(Comparatorsuper T> comparator); //定制排序
带参的sorted函数需要传入Comparator的对象,重写compare(Object o1,object o2)方法

3.map 映射

map方法用于映射每个元素到对应的结果。以下代码片段使用map获取人的姓名

List names = persons.stream().map(Person::getName).collect(Collectors.toList());

4.distinct 去重

distinct 方法用于去掉重复数据。以下代码片段使用filter方法过滤出空字符串并去重

List list = Arrays.asList("abc", "", "bc", "efg", "abc","", "jkl");
List filtered = list.stream().filter(string -> !string.isEmpty()).distinct().collect(Collectors.toList());

5.count 计数

count 方法用于统计集合内对象的数量,以下代码片段使用filter方法过滤出空字符串并计数

List list = Arrays.asList("abc", "", "bc", "efg", "abc","", "jkl");
long count = list.stream().filter(string -> !string.isEmpty()).count();

6.Collectors

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);

二、List根据对象属性分组

底层代码:
1. public static Collector>>
groupingBy(Functionsuper T, ? extends K> classifier) {
return groupingBy(classifier, toList());
}

2. public static
Collector> groupingBy(Functionsuper T, ? extends K> classifier,
Collectorsuper T, A, D> downstream) {
return groupingBy(classifier, HashMap::new, downstream);
}

3. public static extends Map>
Collector groupingBy(Functionsuper T, ? extends K> classifier,
Supplier mapFactory,
Collectorsuper T, A, D> downstream) {
Supplier downstreamSupplier = downstream.supplier();
BiConsumersuper T> downstreamAccumulator = downstream.accumulator();
BiConsumer, T> accumulator = (m, t) -> {
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> merger = Collectors.>mapMerger(downstream.combiner());
@SuppressWarnings("unchecked")
Supplier> mangledFactory = (Supplier>) mapFactory;

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);
}
}

1.根据属性字段分组

 Map> collect = list.stream().collect(Collectors.groupingBy(Person::getName));

2.解决Map不按list顺序问题

 Map> collect = list.stream()
 .collect(Collectors.groupingBy(Person::getName, LinkedHashMap::new,Collectors.toList())); 

3.按照字段升序排序

分组的字段按照TreeMap的规则进行排序放入Map,底层是TreeMap

 Map> collect = list.stream()
 .collect(Collectors.groupingBy(Person::getAge, TreeMap::new, Collectors.toList())); //TreeMap默认以升序排序

4.多重分组

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);

});

三、List 集合统计操作:求和、求最大值、求最小值、求平均值

1.统计数量

long count = Persons.stream().filter(a -> a.getAge() > 5).count();
System.out.println("age > 5的人数 = " + count);

2.求和

int sumAge = persons.stream().mapToInt(Person::getAge).sum();

3.求最大值

int maxAge = persons.stream().mapToInt(Person::getAge).max().getAsInt();

4.求最小值

int minAge = persons.stream().mapToInt(Person::getAge).min().getAsInt();

5.求平均值

double avgAge = persons.stream().mapToInt(Person::getAge).average().getAsDouble();

6.summaryStatistics统计

流用一次就不能用第二次,可以一次性获取一个流的所有统计信息。

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());

你可能感兴趣的:(java,java,后端,list)