在平常的开发工作当中,经常需要对数组进行一些操作,比如根据某个属性值分组,取出某个属性值作为数组等。那么,jdk 1.8为我们提供了便捷的方法,我们应该怎么使用呢?
1:filter:根据某个属性值过滤数据:例如:过滤出来班级编号为 01 的学生
public static void main(String[] args) {
List<StuentVO> list = new ArrayList<>();
StuentVO vo1 = new StuentVO();
StuentVO vo2 = new StuentVO();
StuentVO vo3 = new StuentVO();
vo1.setClassId("01");
vo2.setClassId("01");
vo3.setClassId("02");
list.add(vo1);
list.add(vo2);
list.add(vo3);
// 过滤出来班级编号为 01 的学生
List<StuentVO> sameClass = list.stream().filter(student -> student.getClassId().equals("01")).
collect(Collectors.toList());
}
2:取出某个属性值作为数组,例如:将学生姓名取出来放到数组中
public static void main(String[] args) {
List<StuentVO> list = new ArrayList<>();
StuentVO vo1 = new StuentVO();
StuentVO vo2 = new StuentVO();
StuentVO vo3 = new StuentVO();
vo1.setName("LiMing");
vo2.setName("Lucy");
vo3.setName("Danny");
list.add(vo1);
list.add(vo2);
list.add(vo3);
// 将学生姓名取出来放到数组中
List<String> classIdList = list.stream().map(StuentVO::getName).collect(Collectors.toList());
}
3:分组:根据某个属性分组,例如:根据班级编号分组
public static void main(String[] args) {
List<StuentVO> list = new ArrayList<>();
StuentVO vo1 = new StuentVO();
StuentVO vo2 = new StuentVO();
StuentVO vo3 = new StuentVO();
vo1.setClassId("01");
vo2.setClassId("01");
vo3.setClassId("02");
list.add(vo1);
list.add(vo2);
list.add(vo3);
// 根据班级编号将学生分组
Map<String, List<StuentVO>> studentList = list.stream().collect(Collectors.groupingBy(StuentVO::getClassId));
}
以上为jdk 1.8中lambda表达式在开发中经常用到的方法。
生活就是要不断的学习才精彩。加油!美好的风景一直在路上!