根据偏好对一组人进行排序



我正在设计一个组生成器,它接受诸如"混合性别"、"混合国籍"等偏好。。。我在一个数组列表中列出了学生的名字,然后是国籍和基因集。根据用户输入生成组的最简单方法是,每个组由来自不同国籍或平衡性别的人组成。

public ArrayList<String> readEachWord(String className)
{
ArrayList<String> readword = new ArrayList<String>();
Scanner sc2 = null;
try {
sc2 = new Scanner(new File(className + ".txt"));
} catch (FileNotFoundException e) {
System.out.println("error, didnt find file");
e.printStackTrace();  
}
while (sc2.hasNextLine()) {
Scanner s2 = new Scanner(sc2.nextLine());
while (s2.hasNext()) {
String s = s2.next();
readword.add(s);
}
}
return readword;

}

我用这个来阅读一个文本文件,每一行都有每个学生的名字、国籍和性别。我把它们放在一个ArrayList中,现在正试图找出如何根据用户想要的组号来均匀分配它们。

我使用一个txt文件来存储所有信息,因为这个组生成器是为我的学校定制的。

以下是一些入门知识。这个简短的算法将根据指定的鉴别器(国籍、性别等(对人们进行分类,然后将他们平均分配到指定数量的组中。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Main {
private static class Person {
private String nationality;
private String gender;
public Person(String nationality, String gender) {
this.nationality = nationality;
this.gender = gender;
}

public String getNationality() {
return nationality;
}
public String getGender() {
return gender;
}
@Override
public String toString() {
return "Person{" +
"nationality='" + nationality + "'" +
", gender='" + gender + "'" +
"}";
}
}
public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("DE", "male"),
new Person("DE", "female"),
new Person("DE", "n/a"),
new Person("UK", "female"),
new Person("UK", "female"),
new Person("UK", "female"),
new Person("JP", "trans"),
new Person("JP", "male")
);

int number_of_groups = 3;
Function<Person, String> discriminator = Person::getGender;
AtomicInteger index = new AtomicInteger();
List<List<Person>> groups = new ArrayList<>(people.stream()
.sorted(Comparator.comparing(discriminator))
.collect(Collectors.groupingBy(e -> index.getAndIncrement() % number_of_groups))
.values());
groups.forEach(System.out::println);
}
}

输出:

[Person{nationality='DE', gender='female'}, Person{nationality='UK', gender='female'}, Person{nationality='JP', gender='trans'}]
[Person{nationality='UK', gender='female'}, Person{nationality='DE', gender='male'}]
[Person{nationality='UK', gender='female'}, Person{nationality='DE', gender='n/a'}]

相关内容

  • 没有找到相关文章

最新更新