Java是一门面向对象编程语言。

Lambda表达式操作List集合

Lambda表达式是Java8中一个非常重要的新特性,它允许通过表达式代替功能性的接口,几乎所有的for循环都可以用Lambda表达式来改写,让你的代码更加简洁,开发更加迅速。

下面提供简单的几个Lambda表达式对List集合处理的案例,希望对大家有帮助。


员工表为例:
@ApiModel(value = "employee", description = "员工信息")
public class Employee {
private Integer id; //员工id
private String name; //员工姓名
private Integer age; //员工年龄
private Integer departId; //员工所属部门id
}
测试类:  
public class TestLambda {
// 获取初始化测试数据
private static List<Employee> initList(){
List<Employee> employees = new ArrayList<>();
employees.add(new Employee(1,"apple",22,1));
employees.add(new Employee(2,"banana",33,2));
employees.add(new Employee(3,"mango",22,3));
employees.add(new Employee(4,"pear",41,1));
employees.add(new Employee(5,"grape",54,3));
employees.add(new Employee(6,"orange",68,5));
employees.add(new Employee(7,"peach",29,2));
employees.add(new Employee(8,"raisin",37,1));
return employees;
}

public static void main(String[] args) {

// 获取初始化员工列表集合
List<Employee> employees = initList();


// 1. 获取所有的员工id集合
List<Integer> employeeList =
employees.stream().map(Employee::getId).collect(toList());

// 2. 获取员工id与员工信息的Map集合
Map<Integer, Employee> idEmployeeMap = employees.stream().collect(
Collectors.toMap(Employee::getId, Function.identity()));

// 3. 员工id与员工姓名一一对应
Map<Integer, String> idNameMap = employees.stream().collect(
Collectors.toMap(Employee:: getId, Employee::getName));

// 4. 部门分组,一个部门id对应多个员工信息
Map<Integer, List<Employee>> departGroupMap = employees.stream().collect(
Collectors.groupingBy(Employee::getDepartId));

// 5. 查询当前部门下员工的姓名集合
Map<Integer, List<String>> departNamesMap =
employees.stream().collect(
Collectors.groupingBy(
Employee::getDepartId,
Collectors.mapping(Employee::getName, Collectors.toList())
)
);
}
}
当前位置:Java教程网 »
本文地址:http://www.javajcw.com/34.html
喜欢 or
默认图片
发表我的评论
取消评论