stream java_Java 8 stream一些复杂用法总结

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

@Override

public Map getOperationByShipmentIds(Collection ids) {

return storage

.stream()

.filter(op -> ids.contains(op.getId()))

.collect(Collectors.toMap(MyObj::getId, Function.identity()));

}

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

@Override

public Map> getOperationByShipmentIds(Collection ids) {

return storage

.stream()

.filter(op -> ids.contains(op.getId()))

.collect(Collectors.groupingBy(MyObj::getId));

}

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

List pairs = xxx

Map> = pairs.stream()

.collect(Collectors.groupingBy(IntPair::getV1,

Collectors.mapping(IntPair::getV2, Collectors.toList()))

);

对象列表某一列求和

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

多个list追加到同一个中

List 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 list = new ArrayList<>();

list.add("Hello");

list.add("Hello");

list.add("World");

items.stream().toArray(SignInRankItem[]::new)

Map 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 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 unique = employee.stream()

.collect(collectingAndThen(toCollection(() -> new TreeSet<>(comparingInt(Employee::getId))),

ArrayList::new));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值