2016-07-22 30 views
-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人中,我想找到最受歡迎的運動。

如何根據所有人的年齡的地圖值進行分組,並存儲該年齡組最喜歡的運動項目。

+0

從地圖價值中獲取每個人,按照您的年齡範圍劃分它們,然後從這個年齡段的人羣中橫向搜索,找出哪些運動最受歡迎。繁榮你有你最喜歡的運動。 – Dominic

+0

persons.entrySet()。stream()。collect(Collectors.groupingBy(Person :: getAge)); - 當我嘗試分組時出現錯誤。不知道如何根據年齡從地圖獲取值對象。 – megan

+0

這可能有助於https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html 或者你可以用舊式的方式做一個for-each循環遍歷keySets – Dominic

回答

2

我假設你想在一個單一的陳述中做到這一點?只給你一個想法(我沒有測試過這一點):

public void calculateMostFavouriteForAge(int age) { 

    Map<Integer, String> age2Sport = new HashMap<>(); 

    persons.values().stream() 
      .collect(groupingBy(Person::getAge)) 
      .get(age).stream() 
      .flatMap(p -> p.getFavourites().stream()) 
      .collect(groupingBy(i -> i, HashMap::new, counting())) 
      .entrySet().stream() 
      .max(comparingLong(Map.Entry::getValue)) 
      .ifPresent(entry -> age2Sport.put(age, entry.getKey())); 
} 

當然,這是非常醜陋的和難以理解的代碼,我不會建議寫。順便說一下,如果兩個或多個運動具有相同的最大數量時,該解決方案不是確定性的。