基于偏好的分组不断返回空值

Grouping based on preferences keep returning null value

public class HomeroomMix {


    public void calculate(String className, int number) {
        List<PeopleClass> people = Arrays.asList(
                new PeopleClass("DE", "male"),
                new PeopleClass("DE", "female"),
                new PeopleClass("DE", "n/a"),
                new PeopleClass("UK", "female"),
                new PeopleClass("UK", "female"),
                new PeopleClass("UK", "female"),
                new PeopleClass("JP", "trans"),
                new PeopleClass("JP", "male")
        );


        int number_of_groups = number;

        Function<PeopleClass, String> discriminator = PeopleClass::getGender;

        AtomicInteger index = new AtomicInteger();
        List<List<PeopleClass>> groups = new ArrayList<>(people.stream()
                .sorted(Comparator.comparing(discriminator))
                .collect(Collectors.groupingBy(e -> index.getAndIncrement() % number_of_groups))
                .values());

        groups.forEach(System.out::println);
    }

这是我的人class

 public PeopleClass(String nationality, String gender) {
        this.gender = gender;
        this.nationality = nationality;
    }

    public String getNationality() {
        return nationality;
    }

    public void setNationality(String nationality) {
        this.nationality = nationality;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getHomeRoom() {
        return homeRoom;
    }

    public void setHomeRoom(String homeRoom) {
        this.homeRoom = homeRoom;
    }

    @Override
    public String toString() {
        return name;
    }
}

我正在尝试按喜好对人们进行分组,我最初是在 greenfoot 上编写的,它运行得很好。 但是,我最近想用 javafx 将它嵌入到 intellij 的一个项目中。当我测试时,它的系统输出为空。尽管我还计划循环对象列表而不是在列表中添加每个对象 - 我试过了,但它一直在发送空值。

[null, null, null]
[null, null, null]
[null, null]

我想打印类似

的内容
[person1, person3, person 6]
[person 5, person 2, person 4]
[person 7, person 8]

为什么要对值进行排序并使用 AtomicInteger?试试这个。

首先,我添加了一些名字

int i = 1;
for (PeopleClass p : people) {
    p.setName("Person" + i++);
}

然后我按性别分组


List<List<PeopleClass>> groups = new ArrayList<>(people
        .stream()
        .collect(Collectors
                .groupingBy(PeopleClass::getGender))
        .values());

并打印出来。

groups.forEach(System.out::println);

这是结果

[Person3:n/a]
[Person2:female, Person4:female, Person5:female, Person6:female]
[Person1:male, Person8:male]
[Person7:trans]

注意:您的人员 class 缺少一些东西,例如

  • 一个class声明
  • 字段
  • 和一个 toString() 覆盖(我不得不补一个)。