Java lambda对list分组求和
在Java中,lambda表达式可以方便地用于处理集合操作,比如对List分组并求和。Lambda允许我们在一行简洁的代码中定义函数,这对于简化数据处理特别有用。举个例子,如果我们有一个包含Person对象和它们年龄的List,我们想按年龄段对人群进行分组并计算每个组的总年龄,可以这样做:
import java.util.*;
import java.util.stream.Collectors;
class Person {
String name;
int age;
// constructor and getters/setters...
}
List<Person> people = ...; // 假设已经填充了数据
Map<Integer, Integer> groupedAndSummed = people.stream()
.collect(Collectors.groupingBy(Person::getAge, Collectors.summingInt(Person::getAge)));
// 现在groupedAndSummed是一个Map,key是年龄,value是对应年龄的人群总年龄
在这个片段中,Person::getAge
是lamdba表达式,它获取每个Person对象的年龄作为分组依据,而Collectors.summingInt(Person::getAge)
则表示对于每个分组计算年龄之和。
java 使用lambda对list分组求和
可以使用Java 8中的Stream API和lambda表达式来对List进行分组求和。假设我们有一个List
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Map<Boolean, Integer> result = nums.stream()
.collect(Collectors.partitioningBy(num -> num % 2 == 0,
Collectors.summingInt(Integer::intValue)));
System.out.println(result); // 输出 {false=25, true=30},即奇数之和为25,偶数之和为30
}
}
在上述代码中,我们使用stream()
方法将nums
列表转换为Stream对象,然后使用partitioningBy
方法将Stream按照元素的奇偶性进行分组,返回一个Map<Boolean, Integer>,其中Boolean表示分组的键(true表示偶数,false表示奇数),Integer表示分组的值(即每个分组中元素的和)。最终使用Map的toString()方法将结果输出到控制台上。
java lambda表达式 列表分组求和
好的,可以回答。对于这个问题,可以使用Java 8中的stream API和lambda表达式对列表进行分组,然后使用reduce方法求和。具体实现可以参考以下代码:
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<MyObj> list = Arrays.asList(
new MyObj(1, "A", 10),
new MyObj(1, "B", 20),
new MyObj(2, "C", 30),
new MyObj(2, "D", 40)
);
Map<Integer, Integer> sumByGroup = list.stream()
.collect(Collectors.groupingBy(MyObj::getGroupId,
Collectors.reducing(0, MyObj::getValue, Integer::sum)));
System.out.println(sumByGroup); // 输出 {1=30, 2=70}
}
static class MyObj {
private int groupId;
private String name;
private int value;
public MyObj(int groupId, String name, int value) {
this.groupId = groupId;
this.name = name;
this.value = value;
}
public int getGroupId() {
return groupId;
}
public String getName() {
return name;
}
public int getValue() {
return value;
}
}
}
以上代码将列表按照groupId分组,并且对每个组的value值进行求和。输出的结果为{1=30, 2=70}。
相关推荐
















