-1
我有了一個名字,年齡和喜愛的運動項目列表(游泳,跑步,騎自行車,拳擊,摔跤)一個Person類運動整蠱 - 最喜歡的年齡組中使用lambda表達式
public class Person {
private String name;
private int age;
private List<String> favouriteSports;
public Person(String name, int age, List<String> favourites) {
this.name = name;
this.age = age;
this.favouriteSports= favourites;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public List<String> getFavourites() {
return favouriteSports;
}
}
public class PersonManager {
private Map<String, Person> persons = new HashMap<>();
public void calculateMostFavouriteForAge(){
//1. Group all persons according to age
//2. Get count of favourite sports for every sport in that age group
//3. Store the age and the favourite sport in the age group in a Map.
}
}
的PersonManager有Person名稱和相應Person對象的內部映射。 我想在特定年齡段的所有人中獲得最受歡迎的物品。
假設我有100人(隨機數),並且可以說我有25個20歲年齡段的人,在25歲年齡段的20人中,我想找到最受歡迎的運動。
如何根據所有人的年齡的地圖值進行分組,並存儲該年齡組最喜歡的運動項目。
從地圖價值中獲取每個人,按照您的年齡範圍劃分它們,然後從這個年齡段的人羣中橫向搜索,找出哪些運動最受歡迎。繁榮你有你最喜歡的運動。 – Dominic
persons.entrySet()。stream()。collect(Collectors.groupingBy(Person :: getAge)); - 當我嘗試分組時出現錯誤。不知道如何根據年齡從地圖獲取值對象。 – megan
這可能有助於https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html 或者你可以用舊式的方式做一個for-each循環遍歷keySets – Dominic