簡體   English   中英

如何更改我的語句以在哈希圖中打印對象成員類型的頻率?

[英]How to change my statement to print frequencies of object member type in hashmap?

我創建了具有各種屬性的學生對象的arrayList。 這些屬性包括最喜歡的顏色。 因此,在此n個學生的數組列表中,每個學生都有一個字符串favoriteColor成員變量。

Set<student> studentUnique = new HashSet<student>(studentList);
for (user key : studentUnique) {
    System.out.println(key + ": " + Collections.frequency(studentList, key));
}

我想計算一下這些顏色的頻率,例如,有一百個學生,也許輸出:

red: 50
blue: 20
green: 30

我將學生的arrayList(studentList)放入哈希圖中,但是我不知道如何編寫頻率聲明來獲取喜歡各自顏色的學生的頻率。

studentUnique.stream()
             .collect(Collectors.groupingBy(
                  Student::getColor, 
                  Collectors.counting()))

假設存在getColor

本質上,您正在執行的操作被稱為基於喜歡的顏色的“分組”。

這是另一種方法:

 Map<String, Integer> result = 
         studentList.stream()
                    .collect(toMap(Student::getFavouriteColor, s -> 1, Math::addExact));

這使用了toMap收集器,其中keyMapperStudent::getFavouriteColor即提取學生喜歡的顏色作為地圖鍵的函數。

其次,我們將valueMapper函數s -> 1放置,即一個將Student並返回1作為映射值的函數。

最后,我們提供了一個“合並”函數Math::addExact ,該函數用於根據喜歡的顏色在給定鍵沖突的情況下添加兩個對應的值。

因此,因此,我們將獲得一個String ---> Integer映射,其中映射中的每個條目代表顏色以及該顏色在學生列表中被選為“最喜歡的顏色”的次數。

此外,如果您希望根據出現的結果以升序打印此結果,可以對結果進行排序並按以下方式打印:

studentList.stream()
           .collect(toMap(Student::getFavouriteColor, s -> 1, Math::addExact))
           .entrySet()
           .stream()
           .sorted(Map.Entry.comparingByValue())
           .forEachOrdered(e -> System.out.println(e.getKey() + ":" + e.getValue())); 

所需進口:

import java.util.stream.*;
import static java.util.stream.Collectors.*;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM