[英]sorting objects into an array of elements and an array with several elements
我必须根据他们申请的专业对学生列表进行排序。
我在 object 中的数组变量是String [] specializations;
我介绍的对象是这样的:
x.add (new Students ("Tudorache1", "Marinel", new String [] {"Programmer", "WEB"}, 12, 24, 2020));
x.add (new Students ("Tudorache7", "Marinel2", new String [] {"Operator", "WEB", "Developer"}, 12, 24, 2021));
x.add (new Students ("Tudorache3", "Marinel3", new String [] {"Constructor", "Accountant", "Secretary"}, 12, 24, 2018));
如何按迭代排序以获得:
WEB Tudorache1 Tudorache7
程序员 Tudorache1
操作员 Tudorache7
开发者 Tudorache7
构造函数 Tudorache3
会计师图多拉奇3
图多拉切秘书3
给定的Students
列表应转换为专业化的 map 到Students
class 的第一个字段列表(假设此字段为lastName
)。 然后 map 可以转换为字符串数组 arrays。
这可以使用 Java Stream API 来解决:
public static Map<String, List<String>> mapSpecToNames(List<Students> students) {
return students.stream()
.flatMap(student -> Arrays.stream(student.getSpecializations())
.map(spec -> Arrays.asList(spec, student.getLastName()))
) // Stream<List<String>>
.collect(Collectors.groupingBy(
pair -> pair.get(0), // specialization is a key
LinkedHashMap::new, // keep insertion order
Collectors.mapping(
pair -> pair.get(1), Collectors.toList() // List<String> of names
)
));
}
public String[][] mapToArray(List<Students> students) {
return mapSpecToNames(students)
.entrySet().stream()
.map(e -> Stream.concat(
Stream.of(e.getKey()),
e.getValue().stream()
)
.toArray(String[]::new)
)
.toArray(String[][]::new);
}
测试
List<Students> students = Arrays.asList(
new Students ("Tudorache1", "Marinel", new String [] {"WEB", "Programmer"}, 12, 24, 2020),
new Students ("Tudorache7", "Marine2", new String [] {"Operator", "WEB", "Developer"}, 12, 24, 2020),
new Students ("Tudorache3", "Marine3", new String [] {"Constructor", "Accountant", "Secretary"}, 12, 24, 2020)
);
String[][] result = mapToArray(students);
Arrays.stream(result)
.map(Arrays::toString)
.forEach(System.out::println);
Output:
[WEB, Tudorache1, Tudorache7]
[Programmer, Tudorache1]
[Operator, Tudorache7]
[Developer, Tudorache7]
[Constructor, Tudorache3]
[Accountant, Tudorache3]
[Secretary, Tudorache3]
对于这种排序,学生列表不是很好的数据结构。 例如,您可以通过专业进行迭代。 打印专业化,然后通过 x 运行并打印学生的姓名,如果他的专业化包含专业化。 这不是最佳方式,但可能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.