A
A
antokqer2021-05-11 10:07:40
Java
antokqer, 2021-05-11 10:07:40

How to translate a Collection into a HashMap where K is lenght and V is the number of strings with that length?

This is what I wrote, key is the length of the string, but I just can’t figure out how to find the number of strings with the required character length and pass it to the Map value

public void map(String... array) {
        HashMap<Integer, Integer> hashMap = new HashMap<>();
        Collection <String> collection = Arrays.asList(array);
        HashMap<String, String> map =
                collection.stream()
                        .collect(Collectors.toMap(i -> i.length(), (i -> filter(i -> i.length())));


Tried through loop but can't pass variable to lambda

System.out.println("map = " + map);
        for (String string : collection) {
            int key = string.length();
            int value = collection.stream().filter( i -> (i.lenght() = key));
            hashMap.put(key,value);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2021-05-11
@antokqer

The meaning is to initially create an empty Mapu. Then go through the list of lines once, and for each line:
* calculate its length - x
* take the value from the map by the key x - y
* if y == null, then write the value 1 to the map by the key x
* otherwise write to the map by key x value y + 1
As a result, you get the map you need. Good luck.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question