Stream操作归纳
分组、求和、排序、截取
前言
返回一个{Collector},它对类型为T的输入元素执行分组操作,然后将结果返回到{Map}中。
public static <T, K> Collector<T, ?, Map<K, List<T>>>
groupingBy(Function<? super T, ? extends K> classifier) {
return groupingBy(classifier, toList());
}
根据给定的初始值和关联的函数对流的元素进行计算,并返回计算后的值。
T reduce(T identity, BinaryOperator<T> accumulator);
reduce方法相当于
T result = identity;
for (T element : this stream)
result = accumulator.apply(result, element)
return result;
此方法也可以并行执行。但必须满足如下条件:
1)accumulator.apply(identity,t)= t
2)accumulator函数必须是关联函数。
如果满足以下条件,则运算符或函数op是关联的:
(a op b) op c == a op (b op c)
如果将其扩展为四个术语,可以看出这一点对并行计算的重要性:
a op b op c op d == (a op b) op (c op d)
我们可以并行执行 (a op b)和(c op d)
关联操作的示例包括数字加法,最小值和最大值以及字符串连接。
例如求和
Integer sum = integers.reduce(0, (a, b) -> a+b);
或者
Integer sum = integers.reduce(0, Integer::sum);
reduce操作可以更优雅地并行化,而无需额外的同步并且大大降低了数据竞争的风险
使用
对list按照某一元素进行分组、计算分组后的结果、然后根据结果进行排序。
public class TestMain {
public static void main(String[] args) {
List<Map<String,Object>> listMap = getList();
List<Map<String,Object>> list = listMap.stream().collect(//分组
Collectors.groupingBy(e->e.get("name"))).values()
.stream().map(e -> {//分组后求和
Map<String, Object> map = e.get(0);
map.put("value", e.stream().map(
s -> new BigDecimal(s.get("num").toString())).
reduce(BigDecimal.ZERO, BigDecimal::add));
map.remove("num");
return map;
}).sorted((o1,o2)->{//排序
BigDecimal data1 = new BigDecimal(o1.get("value").toString());
BigDecimal data2 = new BigDecimal(o2.get("value").toString());
return data2.compareTo(data1);
}).limit(5)//取前5
.collect(Collectors.toList());
System.out.println(JSON.toJSONString(list));
}
//数据上传到github
public static List<Map<String,Object>> getList() {
}
}
过滤、去重
前言
collectingAndThen:
public static<T,A,R,RR> Collector<T,A,RR> collectingAndThen(Collector<T,A,R> downstream,
Function<R,RR> finisher) {}
调整集合执行一个额外的转化操作。例如可以调整toList()方法为生成一个不可变的列表。
List<String> people
= people.stream().collect(collectingAndThen(toList(), Collections::unmodifiableList));
toCollection:
将一个集合按照输入的元素顺序累积到一个新集合。
public static <T, C extends Collection<T>>
Collector<T, ?, C> toCollection(Supplier<C> collectionFactory) {}
使用
public class Test1 {
public static void main(String[] args) {
List<Contact> contactList = new ArrayList<Contact>();
Contact obj1 = new Contact();
obj1.setId(1L);
obj1.setName("小白");
obj1.setPhone("15264129801");
Contact obj2 = new Contact();
obj2.setId(2L);
obj2.setName("小明");
obj2.setPhone("15264129802");
Contact obj3 = new Contact();
obj3.setId(3L);
obj3.setName("小白");
obj3.setPhone("15264129803");
Contact obj4 = new Contact();
obj4.setId(4L);
obj4.setName("二狗哒");
obj4.setPhone("0531-76880");
contactList.add(obj1);
contactList.add(obj2);
contactList.add(obj3);
contactList.add(obj4);
contactList = contactList.stream().
filter(e->ValidationUtil.isPhone(e.getPhone())).
collect(Collectors.collectingAndThen(
Collectors.toCollection(() ->
new TreeSet<>(Comparator.comparing(Contact::getName))), ArrayList::new));
contactList.forEach(e->System.out.println(e.getName()));
}
static class Contact {
private Long id;
private String name;
private String phone;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
}
指定分隔符链接
Long[] ids = {1L,2L,3L};
Arrays.stream(ids).map(e->{return String.valueOf(e);})
.collect(Collectors.joining(","));
嵌套List抽取成一个list
List<List<String>> list = new ArrayList<>();
List<String> list2 = new ArrayList<>();
List<String> list3 = new ArrayList<>();
List<String> list4 = new ArrayList<>();
list2.add("123");
list2.add("456");
list3.add("Test");
list3.add("ABCD");
list4.add("noshdfosjf");
list4.add("sfefwemisjfie");
list.add(list2);
list.add(list3);
list.add(list4);
List<String> collect = list.stream().flatMap(Collection::stream).collect(Collectors.toList());
collect.forEach(System.out::println);
参考:
https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html
https://www.cnblogs.com/zklymm/p/13986205.html
https://blog.csdn.net/lijingjingchn/article/details/106856710