Added ListUtils#listToFrequencyMap

This commit is contained in:
Auxilor
2021-11-01 20:00:46 +00:00
parent d95a96f4c6
commit d952dbc61b

View File

@@ -5,7 +5,9 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Utilities / API methods for lists.
@@ -34,4 +36,25 @@ public class ListUtils {
return list;
}
/**
* Convert a list potentially containing duplicates to a map where the value is the frequency of the key.
*
* @param list The list.
* @param <T> The type parameter of the list.
* @return The frequency map.
*/
@NotNull
private static <T> Map<T, Integer> listToFrequencyMap(@NotNull final List<T> list) {
Map<T, Integer> frequencyMap = new HashMap<>();
for (T object : list) {
if (frequencyMap.containsKey(object)) {
frequencyMap.put(object, frequencyMap.get(object) + 1);
} else {
frequencyMap.put(object, 1);
}
}
return frequencyMap;
}
}