I created an arrayList of student objects with various attributes. Among those attributes are favorite color. So in this arraylist of n students, each student has a string favoriteColor member variable.
Set<student> studentUnique = new HashSet<student>(studentList);
for (user key : studentUnique) {
System.out.println(key + ": " + Collections.frequency(studentList, key));
}
I would like to count the frequency of said colors so for example with a hundred students, maybe output:
red: 50
blue: 20
green: 30
I put my arrayList of students (studentList) into a hashmap but I don't know how to write my frequency statement to get the frequency of students that like their respective colors.
studentUnique.stream()
.collect(Collectors.groupingBy(
Student::getColor,
Collectors.counting()))
Assuming getColor
exists.
Essentially what you're doing is called "grouping" based on the favourite color.
Here is another approach:
Map<String, Integer> result =
studentList.stream()
.collect(toMap(Student::getFavouriteColor, s -> 1, Math::addExact));
This uses the toMap
collector, where the keyMapper
is Student::getFavouriteColor
ie a function extracting the students favourite color as the map key.
Second, we place the valueMapper
function s -> 1
ie a function taking a Student
and return 1
as the map value.
Lastly, we provide a "merge" function Math::addExact
which is a function used to add two corresponding values given a key clash based on the favourite colour.
So, as a result, we will have a map from String
---> Integer
where each entry in the map represents the color and the number of times that color has been chosen as a "favourite color" amongst the students' list.
Further, if you want to print this result in an ascending order based on occurrences, you can sort the result and print as follows:
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()));
imports needed:
import java.util.stream.*;
import static java.util.stream.Collectors.*;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.