从Java 8流中获取N(3)个列表(基于ENUM性别(男性,女性,其他)),并基于ENUM

时间:2019-07-09 21:48:07

标签: java collections java-8 java-stream

如何基于性别枚举类型创建N个列表?如果我有3个可能的GENDER枚举(男,女,其他),则需要3个列表。如何使用Java 8 Streams API实现此目标?

在这种情况下,我需要带有3个键的MAP。 sexmap.get(GENDER.male)。

Map<GENDER, List<Person>> genderMap;

尝试使用partitioningBy

Map<Boolean, List<Person>> genderMap= people.stream().collect(Collectors.partitioningBy(malePredicate()));

System.out.println("MALE "+genderMap.get(true));
System.out.println("FEMALE "+genderMap.get(false));

private static Predicate<Person> malePredicate(){
    return p ->  p.getGender() != null && p.getGender().equalsIgnoreCase("male");
}

private static Predicate<Person> femalePredicate(){
    return p ->  p.getGender() != null && p.getGender().equalsIgnoreCase("female");
}
  • 男性 [人员[id = 1,姓名= SAMPLE_1,年龄= 11,性别=男性,工资= 100, monthExpenseAmount = 120.00],人员[id = 2,姓名= SAMPLE_2,年龄= 12, 性别=男性,工资= 100,每月ExpenseAmount = 120.00]]
  • 女性 [人员[id = 0,姓名= SAMPLE_0,年龄= 10,性别=其他,工资= 100, monthExpenseAmount = 120.00],人员[id = 3,姓名= SAMPLE_3,年龄= 13, 性别=女性,工资= 100,每月ExpenseAmount = 100.00],人员[id = 4, 名字= SAMPLE_4,年龄= 14,性别=女,萨尔= 100, monthExpenseAmount = 100.00],人员[id = 5,姓名= SAMPLE_5,年龄= 15, 性别=女性,工资= 100,每月ExpenseAmount = 100.00]]

2 个答案:

答案 0 :(得分:2)

使用groupingBy()toList()

Map<Gender, List<Person>> genderMap = people.stream()
        .collect(Collectors.groupingBy(Person::getGender, Collectors.toList()));

有关演示,请参见IDEONE

答案 1 :(得分:0)

.partitioningBy()用于将结果分成2组。

您正在寻找.groupingBy()

Map<Gender, List<Person>> genderMap = people.stream()
     .collect(Collectors.groupingBy(Person::getGender));