これが私のコードです:
public class StudentData {
public static List<Student> getData() {
return Arrays.asList(
new Student(1, "a1", 1, Arrays.asList("cricket", "football", "basketball")),
new Student(2, "a2", 1, Arrays.asList("chess", "football")),
new Student(3, "a3", 2, Arrays.asList("running")),
new Student(4, "a4", 2, Arrays.asList("throwball", "football")),
new Student(5, "a5", 3, Arrays.asList("cricket", "basketball")),
new Student(6, "a6", 4, Arrays.asList("cricket")), new Student(7, "a7", 5, Arrays.asList("basketball")),
new Student(8, "a8", 6, Arrays.asList("football")),
new Student(9, "a9", 8, Arrays.asList("tennis", "swimming")),
new Student(10, "a10", 8, Arrays.asList("boxing", "running")),
new Student(11, "a11", 9, Arrays.asList("cricket", "football")),
new Student(12, "a12", 11, Arrays.asList("tennis", "shuttle")),
new Student(13, "a13", 12, Arrays.asList("swimming"))
);
}
}
趣味に基づいて学生をグループ化する方法。私は以下のコードを試しました:
List<Student> data = StudentData.getData();
data.stream().collect(Collectors.groupingBy(s -> s.getHobbies().stream()));
それは正しい答えを与えていません。
基本的には、左側が趣味、右側が生徒(この場合は逆でも構いません)Stream
であるPair
(AbstractMap.SimpleEntry
ここで選択します)から作成されたが必要です。
後でそれらに基づいてそれらをグループ化Hobby
します(あなたの場合は文字列です)。
data.stream()
.flatMap(student -> student.getHobbies().stream().map(hobby -> new SimpleEntry<>(hobby, student)))
.collect(Collectors.groupingBy(
Entry::getKey,
Collectors.mapping(Entry::getValue, Collectors.toList())
));
Entry::getKey
キーを取得するメソッド参照であるため、ラムダ式として記述することもできます。
Collectors.groupingBy(entry -> entry.getKey())
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加