Java 8 stream一些复杂用法总结

传入数组ids,在list<Obj>上操作,找出Obj中id想匹配的,并且按照id进行collect成map(这里假设找出来的按照id不重复)

@Override
public Map<Integer, MyObj> getOperationByShipmentIds(Collection<Integer> ids) {
    return storage
            .stream()
            .filter(op -> ids.contains(op.getId()))
            .collect(Collectors.toMap(MyObj::getId, Function.identity()));
}

接上面的,假设id可以重复:

@Override
public Map<Integer, List<MyObj>> getOperationByShipmentIds(Collection<Integer> ids) {
    return storage
            .stream()
            .filter(op -> ids.contains(op.getId()))
            .collect(Collectors.groupingBy(MyObj::getId));
}

更复杂一点,假设不是一个MyObj了,而是一个Pair

List<IntPair> pairs = xxx

Map<Integer, List<Integer>> = pairs.stream()
                .collect(Collectors.groupingBy(IntPair::getV1,
                        Collectors.mapping(IntPair::getV2, Collectors.toList()))
                );

对象列表某一列求和

list.values().stream().mapToInt(obj -> obj.getIntField()).sum();

多个list追加到同一个中

List<MyObject> list = services.stream()
                              .flatMap(s -> s.getObjects().stream())
                              .collect(Collectors.toList());

类似wordCount计数

import java.util.*;
import java.util.stream.*;

class Test {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();

        list.add("Hello");
        list.add("Hello");
        list.add("World");
items.stream().toArray(SignInRankItem[]::new)
        Map<String, Long> counted = list.stream()
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        System.out.println(counted);
    }
}

使用Lambda实现分段chunk

AtomicInteger counter = new AtomicInteger();

stream.collect(groupingBy(x->counter.getAndIncrement()/chunkSize))
    .values()
    .forEach(database::flushChunk);

跑个题,上面的那个也可以用apache commons搞定

ListUtils.partition(list, batchSize)

并发线程数

System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "8")

排序

list.stream()
.sorted((f1, f2) -> Long.compare(f2.lastModified(), f1.lastModified())
....

排序2

list.stream()
.sorted(Comparator.comparingLong(File::lastModified))
....

排序2(反序)

list.stream()
.sorted(Comparator.comparingLong(File::lastModified).reversed())
....

多字段排序

public int compare(Obj o1, Obj o2) {
        return Objects.compare(o1, o2,
                Comparator.comparingLong(Obj::getF1)
                        .thenComparing(Obj::getF2)
        );
}

设置并发stream线程数

System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "10");

collect map并且处理dup key问题

Map<String, String> phoneBook = people.stream()
  .collect(Collectors.toMap(Person::getName, Person::getAddress, (p1, p2) -> p1));

stream转数组

items.stream().toArray(XXObject[]::new)
// or
items.stream().toArray(size -> new XXX[size])

按照某个字段去重

import static java.util.Comparator.comparingInt;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;

...
List<Employee> unique = employee.stream()
                                .collect(collectingAndThen(toCollection(() -> new TreeSet<>(comparingInt(Employee::getId))),
                                                           ArrayList::new));

 

 

 

 

 

 

 

Leave a Reply

Your email address will not be published.