[英]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.