task №1 as key - String, and value - character frequency
In order to obtain the frequency of every character, you need to flatten each string in a list (i.e. split every string into characters).
Since Java 9 we can use method chars() which returns a stream of characters represented with int primitives.
flatMapToInt(String::chars) will produce an IntStream, containing characters from every string in the given list.
Then mapToObj() creates a single-character string for every stream element.
To generate the map of frequencies, we can utilize collector Collectors.groupingBy(). Function.identity() is used as the first argument is an equivalent of e -> e, it's just a way to tell that stream elements will be used as a key without any changes. The second argument is a downstream collector Collectors.counting(), that generates the number of elements mapped to a particular key.
public static Map<String, Long> getCharacterFrequency(List<String> list) {
return list.stream() // Stream<String>
.flatMapToInt(String::chars) // IntStream
.mapToObj(ch -> String.valueOf((char) ch)) // String<String>
.collect(Collectors.groupingBy(Function.identity(),
Collectors.counting()));
}
task №2 as key - String, and value - string converted to integer
You can do it by using a flavor of collector Collectors.toMap() that expects three arguments:
- keyMapper - a function that produces the key from a stream element;
- valueMapper - a function that produces the value from a stream element;
- mergeFunction - a function that determines how to resolve a situation when two values happens to be mapped to the same key.
Although, the mergeFunction in the code below is not doing anything special, it needs to be provided, otherwise the first encountered duplicate will cause an IllegalStateException.
public static Map<String, Integer> getStringValuesMappedToInts(List<String> list) {
return list.stream()
.collect(Collectors.toMap(Function.identity(), // key (String)
Integer::valueOf, // value (Integer)
(v1, v2) -> v1)); // function that resolves collisions
}
main() - demo
public static void main(String[] args) {
List<String> source = List.of("5", "7", "57", "59", "5", "8", "99", "9", "8");
// task 1
System.out.println("task 1:\n" + getCharacterFrequency(source));
// task 2
System.out.println("task 2:\n" + getStringValuesMappedToInts(source));
}
Output
task 1:
{5=4, 7=2, 8=2, 9=4}
task 2:
{99=99, 57=57, 59=59, 5=5, 7=7, 8=8, 9=9}
Map<String,String>. Note thate->eandFunction.identity()do the same thing.5 = 5value in your map, not two.