Java8stream分组合并使⽤很简单,功能很强⼤
package com.lee;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Buss> bussList = new ArrayList<>();
bussList.add(new Buss("a",10,0.3));
bussList.add(new Buss("b",3,0.8));
bussList.add(new Buss("c",5,2.0));
bussList.add(new Buss("b",30,3.2));
bussList.add(new Buss("c",20,0.1));
List<Buss> st = new ArrayList<>();
bussList.stream()
.upingBy(Buss::getName)) //分组(Name can't be null)
.forEach((k,v) -> {
Optional<Buss> sum = v.stream().reduce((v1,v2) -> { //合并
v1.Count()+v2.getCount());
v1.Value()+v2.getValue());
return v1;
});
st.Else(new Buss("other",0,0.0)));
});
System.out.println(st);
}
}
class Buss {
private String name;
private int count;
private double value;
public Buss(String name, int count, double value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCount() {
return count;
}
public void setCount(int count) {
}
public double getValue() {
return value;
java stream}
public void setValue(double value) {
this.value = value;
}
@Override
public String toString() {
return"Buss{" +
"name='" + name + '\'' +
", count=" + count +
", value=" + value +
'}';
}
}
Output
[Buss{name='a', count=10, value=0.3}, Buss{name='b', count=33, value=4.0}, Buss{name='c', count=25, value=2.1}]
如何根据两个字段排序
可以再 model⾥⾯ ,写⼀个类似的⽅法即可
下例,分组的key 就是 name+value
public String groupField() {
return getName()+"-"+getValue();
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论