2020-10-21 超、凢脫俗 2022-12-17 02:23 77阅读 0赞 > java 8的lambda表达式提供了一些方便list操作的方法,主要涵盖**分组、过滤、求和、最值、排序、去重**。跟之前的传统写法对比,能少写不少代码 **实体类** import java.math.BigDecimal; import java.util.Date; public class User { private Long id; /** * 姓名 */ private String name; /** * 年龄 */ private int age; /** * 工号 */ private String jobNumber; /** * 性别 */ private String sex; /** * 入职日期 */ private Date entryDate; /** * 家庭成员数量 */ private BigDecimal familyMemberQuantity; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getJobNumber() { return jobNumber; } public void setJobNumber(String jobNumber) { this.jobNumber = jobNumber; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Date getEntryDate() { return entryDate; } public void setEntryDate(Date entryDate) { this.entryDate = entryDate; } public BigDecimal getFamilyMemberQuantity() { return familyMemberQuantity; } public void setFamilyMemberQuantity(BigDecimal familyMemberQuantity) { this.familyMemberQuantity = familyMemberQuantity; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + ", jobNumber='" + jobNumber + '\'' + ", sex='" + sex + '\'' + ", entryDate=" + entryDate + ", familyMemberQuantity=" + familyMemberQuantity + '}'; } } 1.分组 通过groupingBy可以分组指定字段 //分组 Map<String, List<User>> groupBySex = userList.stream().collect(Collectors.groupingBy(User::getSex)); //遍历分组 for (Map.Entry<String, List<User>> entryUser : groupBySex.entrySet()) { String key = entryUser.getKey(); List<User> entryUserList = entryUser.getValue(); for (User user: entryUserList) { System.out.println(key + ":" +user.toString()); } } 2.过滤 通过filter方法可以过滤某些条件 //过滤 //排除掉工号为a2的用户 List<User> userCommonList = userList.stream().filter(a -> !a.getJobNumber().equals("a2")).collect(Collectors.toList()); for (User user:userCommonList) { System.out.println(user.toString()); } 3.求和 分基本类型和大数类型求和,基本类型先mapToInt,然后调用sum方法,大数类型使用reduce调用BigDecimal::add方法 //求和 //基本类型 int sumAge = userList.stream().mapToInt(User::getAge).sum(); System.out.println(sumAge); //BigDecimal求和 //user3.setFamilyMemberQuantity(new BigDecimal(2)); 注释会报错 BigDecimal totalQuantity = userList.stream().map(User::getFamilyMemberQuantity).reduce(BigDecimal.ZERO, BigDecimal::add); System.out.println(totalQuantity); //user3.setFamilyMemberQuantity(new BigDecimal(2)); 注释不会报错 BigDecimal totalQuantity2 = userList.stream().map(User::getFamilyMemberQuantity).reduce(BigDecimal.ZERO, BigDecimalUtils::sum); System.out.println(totalQuantity2); 上面的求和不能过滤bigDecimal对象为null的情况,可能会报空指针,这种情况,我们可以用filter方法过滤,或者重写求和方法 重写求和方法 import java.math.BigDecimal; public class BigDecimalUtils { public static BigDecimal ifNullSet0(BigDecimal in) { if (in != null) { return in; } return BigDecimal.ZERO; } public static BigDecimal sum(BigDecimal ...in){ BigDecimal result = BigDecimal.ZERO; for (int i = 0; i < in.length; i++){ result = result.add(ifNullSet0(in[i])); } return result; } } 使用重写的方法 BigDecimal totalQuantity2 = userList.stream().map(User::getFamilyMemberQuantity).reduce(BigDecimal.ZERO, BigDecimalUtils::sum); 判断对象空 stream.filter(x -> x!=null) stream.filter(Objects::nonNull) 判断字段空 stream.filter(x -> x.getDateTime()!=null) 4.最值 求最小与最大,使用min max方法 //最小 Date minEntryDate = userList.stream().map(User::getEntryDate).min(Date::compareTo).get(); //最大 Date maxEntryDate = userList.stream().map(User::getEntryDate).max(Date::compareTo).get(); System.out.println(minEntryDate); System.out.println(maxEntryDate); 5.List 转map /** * List -> Map * 需要注意的是: * toMap 如果集合对象有重复的key,会报错Duplicate key .... * user1,user2的id都为1。 * 可以用 (k1,k2)->k1 来设置,如果有重复的key,则保留key1,舍弃key2 */ Map<Long, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, a -> a,(k1,k2)->k1)); System.out.println(userMap); 6.排序 可通过Sort对单字段多字段排序 //排序 //单字段排序,根据id排序 userList.sort(Comparator.comparing(User::getId)); //多字段排序,根据id,年龄排序 userList.sort(Comparator.comparing(User::getId).thenComparing(User::getAge)); System.out.println(userList); 7.去重 可通过distinct方法进行去重 //去重 List<Long> idList = new ArrayList<Long>(); idList.add(1L); idList.add(1L); idList.add(2L); List<Long> distinctIdList = idList.stream().distinct().collect(Collectors.toList()); System.out.println(distinctIdList); 8.获取list某个字段组装新list //获取list对象的某个字段组装成新list List<Long> userIdList = userList.stream().map(a -> a.getId()).collect(Collectors.toList()); System.out.println(userIdList); 9.批量设置list列表字段为同一个值 userList.stream().forEach(a -> a.setJobNumber("0")); System.out.println(userList); 全部代码: import java.math.BigDecimal; import java.util.Date; public class User { private Long id; /** * 姓名 */ private String name; /** * 年龄 */ private int age; /** * 工号 */ private String jobNumber; /** * 性别 */ private String sex; /** * 入职日期 */ private Date entryDate; /** * 家庭成员数量 */ private BigDecimal familyMemberQuantity; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getJobNumber() { return jobNumber; } public void setJobNumber(String jobNumber) { this.jobNumber = jobNumber; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Date getEntryDate() { return entryDate; } public void setEntryDate(Date entryDate) { this.entryDate = entryDate; } public BigDecimal getFamilyMemberQuantity() { return familyMemberQuantity; } public void setFamilyMemberQuantity(BigDecimal familyMemberQuantity) { this.familyMemberQuantity = familyMemberQuantity; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + ", jobNumber='" + jobNumber + '\'' + ", sex='" + sex + '\'' + ", entryDate=" + entryDate + ", familyMemberQuantity=" + familyMemberQuantity + '}'; } } import java.math.BigDecimal; public class BigDecimalUtils { public static BigDecimal ifNullSet0(BigDecimal in) { if (in != null) { return in; } return BigDecimal.ZERO; } public static BigDecimal sum(BigDecimal ...in){ BigDecimal result = BigDecimal.ZERO; for (int i = 0; i < in.length; i++){ result = result.add(ifNullSet0(in[i])); } return result; } } import java.math.BigDecimal; import java.util.*; import java.util.stream.Collectors; public class Test { private static List<User> userList = new ArrayList<>(); static { User user1 = new User(); user1.setId(1L); user1.setName("roc"); user1.setAge(16); user1.setJobNumber("a1"); user1.setSex("man"); user1.setEntryDate(new Date()); user1.setFamilyMemberQuantity(new BigDecimal(2)); userList.add(user1); User user2 = new User(); user2.setId(2L); user2.setName("ling"); user2.setAge(15); user2.setJobNumber("a2"); user2.setSex("woman"); user2.setEntryDate(new Date(2010-1900,1,10)); user2.setFamilyMemberQuantity(new BigDecimal(2)); userList.add(user2); User user3 = new User(); user3.setId(3L); user3.setName("rocling"); user3.setJobNumber("a12"); user3.setSex("man"); user3.setEntryDate(new Date()); user3.setFamilyMemberQuantity(new BigDecimal(2)); userList.add(user3); } public static void main(String[] args) { //分组 Map<String, List<User>> groupBySex = userList.stream().collect(Collectors.groupingBy(User::getSex)); //遍历分组 for (Map.Entry<String, List<User>> entryUser : groupBySex.entrySet()) { String key = entryUser.getKey(); List<User> entryUserList = entryUser.getValue(); for (User user: entryUserList) { System.out.println(key + ":" +user.toString()); } } System.out.println("----------------------------------------------------------------------------------------------------"); //过滤 //排除掉工号为a2的用户 List<User> userCommonList = userList.stream().filter(a -> !a.getJobNumber().equals("a2")).collect(Collectors.toList()); for (User user:userCommonList) { System.out.println(user.toString()); } System.out.println("----------------------------------------------------------------------------------------------------"); //求和 //基本类型 int sumAge = userList.stream().mapToInt(User::getAge).sum(); System.out.println(sumAge); //BigDecimal求和 //user3.setFamilyMemberQuantity(new BigDecimal(2)); 注释会报错 BigDecimal totalQuantity = userList.stream().map(User::getFamilyMemberQuantity).reduce(BigDecimal.ZERO, BigDecimal::add); System.out.println(totalQuantity); //user3.setFamilyMemberQuantity(new BigDecimal(2)); 注释不会报错 BigDecimal totalQuantity2 = userList.stream().map(User::getFamilyMemberQuantity).reduce(BigDecimal.ZERO, BigDecimalUtils::sum); System.out.println(totalQuantity2); System.out.println("----------------------------------------------------------------------------------------------------"); //最小 Date minEntryDate = userList.stream().map(User::getEntryDate).min(Date::compareTo).get(); //最大 Date maxEntryDate = userList.stream().map(User::getEntryDate).max(Date::compareTo).get(); System.out.println(minEntryDate); System.out.println(maxEntryDate); System.out.println("----------------------------------------------------------------------------------------------------"); /** * List -> Map * 需要注意的是: * toMap 如果集合对象有重复的key,会报错Duplicate key .... * user1,user2的id都为1。 * 可以用 (k1,k2)->k1 来设置,如果有重复的key,则保留key1,舍弃key2 */ Map<Long, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, a -> a,(k1,k2)->k1)); System.out.println(userMap); System.out.println("----------------------------------------------------------------------------------------------------"); //排序 //单字段排序,根据id排序 userList.sort(Comparator.comparing(User::getId)); //多字段排序,根据id,年龄排序 userList.sort(Comparator.comparing(User::getId).thenComparing(User::getAge)); System.out.println(userList); System.out.println("----------------------------------------------------------------------------------------------------"); //去重 List<Long> idList = new ArrayList<Long>(); idList.add(1L); idList.add(1L); idList.add(2L); List<Long> distinctIdList = idList.stream().distinct().collect(Collectors.toList()); System.out.println(distinctIdList); System.out.println("----------------------------------------------------------------------------------------------------"); //获取list对象的某个字段组装成新list List<Long> userIdList = userList.stream().map(a -> a.getId()).collect(Collectors.toList()); System.out.println(userIdList); System.out.println("----------------------------------------------------------------------------------------------------"); userList.stream().forEach(a -> a.setJobNumber("0")); System.out.println(userList); } }
相关 20201021-01 QT 程序独立运行时,出现CMD窗口 消除办法 效果 QT 的程序脱离 Qtcreator 直接双击运行出现 CMD 输出debug 调试信息 解决方案: 1 编译条件选一下 Release,这种会默认关闭 deb 亦凉/ 2022年12月17日 02:23/ 0 赞/ 57 阅读
还没有评论,来说两句吧...