我有一份学生名单,每个学生都可以注册几个科目。 因此,每个学生都有一个主题列表。我想使用java 8功能对Subject进行分组。 我无法找到方法。任何帮助将不胜感激。
答案 0 :(得分:1)
这只是使用groupBy
的示例。您可以在网上找到许多其他示例。 [此示例取自here]
按价格分组商品:Collectors.groupingBy
和Collectors.mapping
示例
public static void main(String[] args) {
//3 apple, 2 banana, others 1
List<Item> items = Arrays.asList(
new Item("apple", 10, new BigDecimal("9.99")),
new Item("banana", 20, new BigDecimal("19.99")),
new Item("orang", 10, new BigDecimal("29.99")),
new Item("watermelon", 10, new BigDecimal("29.99")),
new Item("papaya", 20, new BigDecimal("9.99")),
new Item("apple", 10, new BigDecimal("9.99")),
new Item("banana", 10, new BigDecimal("19.99")),
new Item("apple", 20, new BigDecimal("9.99"))
);
//group by price
Map<BigDecimal, List<Item>> groupByPriceMap =
items.stream().collect(Collectors.groupingBy(Item::getPrice));
System.out.println(groupByPriceMap);
// group by price, uses 'mapping' to convert List<Item> to Set<String>
Map<BigDecimal, Set<String>> result =
items.stream().collect(
Collectors.groupingBy(Item::getPrice,
Collectors.mapping(Item::getName, Collectors.toSet())
)
);
System.out.println(result);
}
输出
{
19.99=[
Item{name='banana', qty=20, price=19.99},
Item{name='banana', qty=10, price=19.99}
],
29.99=[
Item{name='orang', qty=10, price=29.99},
Item{name='watermelon', qty=10, price=29.99}
],
9.99=[
Item{name='apple', qty=10, price=9.99},
Item{name='papaya', qty=20, price=9.99},
Item{name='apple', qty=10, price=9.99},
Item{name='apple', qty=20, price=9.99}
]
}
//group by + mapping to Set
{
19.99=[banana],
29.99=[orang, watermelon],
9.99=[papaya, apple]
}
答案 1 :(得分:1)
我的一位朋友提出了这个解决方案并且工作正常
package grpBy;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
class Pair {
Subject sub1;
Student student;
public Pair(Student student, Subject sub1 ) {
this.sub1 = sub1;
this.student = student;
}
public String getSub1() {
return sub1.name;
}
public String getStudent() {
return student.name;
}
static Pair of(Student stu, Subject sub) {
return new Pair( stu, sub);
}
}
public class Test2 {
public static void main(String[] args) {
Subject maths = new Subject("maths", 1);
Subject chemi = new Subject("chemi", 1);
Subject phy = new Subject("phy", 1);
Subject bio = new Subject("bio", 1);
List<Subject> s1 = new ArrayList<>();
s1.add(maths);
s1.add(chemi);
List<Subject> s2 = new ArrayList<>();
s2.add(maths);
s2.add(phy);
List<Subject> s3 = new ArrayList<>();
s3.add(bio);
s3.add(phy);
Student jack = new Student(1, "jack", s1);
Student jil = new Student(2, "jil", s2);
Student john = new Student(3, "john", s3);
List<Student> students = new ArrayList();
students.add(jack);
students.add(jil);
students.add(john);
Map<String, List<String>> m = students.stream().
flatMap(student -> student.subjects.stream().map(subject -> Pair.of(student, subject))).
collect(Collectors.groupingBy(e -> e.getSub1(),
Collectors.mapping(e -> e.getStudent(),
Collectors.toList())));
System.out.println(m);
}
}