我希望找出学生中最受欢迎的前N项运动。其中,N是一个参数。
我分三步完成了这个任务,但并不满意。我正在尝试将其优化为一步完成。
以下是我的完整代码和解决方案:
public class Person {
private UUID id;
private String name;
private List<Sport> sports = new ArrayList<>();
//getter and setters + constructor
}
这是“体育课”:
public class Sport {
private String name;
public Sport(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
这是我的数据以及提取前三最受欢迎的运动的逻辑:
public static void main(String[] args) {
// most popular sports
Sport football = new Sport("Football");
Sport tennis = new Sport("Tennis");
Sport basketBall = new Sport("BasketBall");
Sport handball = new Sport("Handball");
Sport swimming = new Sport("Swimming");
Sport running = new Sport("Running");
Sport climbing = new Sport("Climbing");
List<Person> people = new ArrayList<>();
people.add(new Person(UUID.randomUUID(), "Bob", Arrays.asList(football, handball)));
people.add(new Person(UUID.randomUUID(), "Tom", Arrays.asList(football, basketBall, tennis)));
people.add(new Person(UUID.randomUUID(), "Tim", Arrays.asList(climbing, handball, football)));
people.add(new Person(UUID.randomUUID(), "Marc", Arrays.asList(football, basketBall)));
people.add(new Person(UUID.randomUUID(), "Gerard", Arrays.asList(tennis, handball)));
people.add(new Person(UUID.randomUUID(), "Claudia", Arrays.asList(running, handball)));
people.add(new Person(UUID.randomUUID(), "Sara", Arrays.asList(football, climbing)));
people.add(new Person(UUID.randomUUID(), "Laura", Arrays.asList(football)));
people.add(new Person(UUID.randomUUID(), "Mo", Arrays.asList(football, tennis)));
//Step 1 - Merge all the sports lists of all students
List<Sport> allSports = new ArrayList<>();
for (Person person : people) {
allSports.addAll(person.getSports());
}
// Step 2 - Transfor into a Map with groupBy and count
Map<Sport, Long> collect = allSports.stream().collect(groupingBy(Function.identity(), counting()));
// Return top 3 most popular sports
collect.entrySet().stream()
.sorted(Map.Entry.<Sport, Long>comparingByValue().reversed())
.limit(3)
.forEach(s -> System.out.println(s.getKey().getName()));
}
输出:
Football
Handball
Tennis