import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Item> items = new ArrayList<>();
items.add(new Item("Group1", 10, 2.5));
items.add(new Item("Group1", 20, 3.5));
items.add(new Item("Group2", 15, 4.0));
items.add(new Item("Group2", 25, 5.0));
List<Summary> summaries = items.stream()
.collect(Collectors.groupingBy(Item::getProperty1))
.entrySet()
.stream()
.map(entry -> {
String property1 = entry.getKey();
int sumOfProperty2 = entry.getValue().stream()
.mapToInt(Item::getProperty2)
.sum();
double sumOfProperty3 = entry.getValue().stream()
.mapToDouble(Item::getProperty3)
.sum();
return new Summary(property1, sumOfProperty2, sumOfProperty3);
})
.collect(Collectors.toList());
summaries.forEach(System.out::println);
}
static class Item {
private String property1;
private int property2;
private double property3;
public Item(String property1, int property2, double property3) {
this.property1 = property1;
this.property2 = property2;
this.property3 = property3;
}
public String getProperty1() {
return property1;
}
public int getProperty2() {
return property2;
}
public double getProperty3() {
return property3;
}
}
static class Summary {
private String property1;
private int sumOfProperty2;
private double sumOfProperty3;
public Summary(String property1, int sumOfProperty2, double sumOfProperty3) {
this.property1 = property1;
this.sumOfProperty2 = sumOfProperty2;
this.sumOfProperty3 = sumOfProperty3;
}
public String getProperty1() {
return property1;
}
public int getSumOfProperty2() {
return sumOfProperty2;
}
public double getSumOfProperty3() {
return sumOfProperty3;
}
@Override
public String toString() {
return "Summary{" +
"property1='" + property1 + '\'' +
", sumOfProperty2=" + sumOfProperty2 +
", sumOfProperty3=" + sumOfProperty3 +
'}';
}
}
}
java8集合对象有三个属性String,Integer,Double,现在请你根据第一个属性对集合进行分组分别求出另外两个属性的和,并将结果封装到新集合对象中
最新推荐文章于 2023-12-10 19:08:17 发布