jdk8 流式数据处理太灵活,一下了还不太好掌握 ,下面记录一些操作,方便使用的时候参考
public void testCodeSum() {
Foo foo1 = new Foo(1, 2, 5);
Foo foo2 = new Foo(2, 23, 6);
Foo foo3 = new Foo(2, 6, 7);
List<Foo> list = new ArrayList<>(4);
list.add(foo1);
list.add(foo2);
list.add(foo3);
Map<Integer, IntSummaryStatistics> collect = list.stream().collect(
Collectors.groupingBy(Foo::getCode, Collectors.summarizingInt(Foo::getCount)));
// 输出求结果的和
Map slist = list.stream().collect(Collectors.groupingBy(foo -> foo.getCode(), Collectors.summingInt(fs -> fs.getCount())));
System.out.println("sumCount: " + slist.toString());
Foo fooobj = list.stream().reduce(
(x, y) -> new Foo((x.getCode() + y.getCode()), (x.getCount() + y.getCount()), (x.getId() + y.getId()))).orElse(
new Foo(1, 2, 3));
System.out.println("reduce: " + fooobj.getId() + ", " + fooobj.getCount() + ", " + fooobj.getCode());
IntSummaryStatistics statistics2 = collect.get(2);
System.out.println(statistics2.getSum());
System.out.println(statistics2.getAverage());
System.out.println(statistics2.getMax());
System.out.println(statistics2.getMin());
System.out.println(statistics2.getCount());
}
// @Test 列表中的多个元素的属性求和并返回
public void test() {
List<A> list = new ArrayList<A>();
list.add(new A(1, 2));
list.add(new A(100, 200));
A a = list.stream().reduce((x, y) -> new A((x.getPrincipal() + y.getPrincipal()), (x.getFee() + y.getFee()))).orElse(new A(0, 0));
System.out.println(a);
}
代码1
class A { int principal = 0; int fee = 0; public A(int principal, int fee) { super(); this.principal = principal; this.fee = fee; } public A() { super(); // TODO Auto-generated constructor stub } public int getPrincipal() { return principal; } public void setPrincipal(int principal) { this.principal = principal; } public int getFee() { return fee; } public void setFee(int fee) { this.fee = fee; } @Override public String toString() { return "A [principal=" + principal + ", fee=" + fee + "]"; } }
代码2
class Foo { private int code; private int count; private int id; public Foo(int code, int count, int id) { this.code = code; this.count = count; this.id = id; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
简单使用, 以后再详细实践