Search code examples
javalambdajava-8hashmapunary-function

HashMap in Unary Functional Interface with Lambda in Java 8


I'm studying for Java 8 Lambda and Unary Functional Interface. I have a practice assignment about "Function" class using HashMap, which the following steps to do:

  1. Create a variable of type Function<Set, Map> that receives a Set and creates a HashMap using lambda expressions

  2. Put words in the map, using as key the uppercase first letter of that word

  3. Execute lambda expression and view the result

I trying in the following way, but it doesn't work. I think that the problem is in the lambda expression, but I want to understand how I have to do (for simplicity I put the same word as key). In this way, the result is "null".

import java.util.*;
import java.util.function.Function;

public class FunctionTest {

public static void main(String[] args) {
        HashSet<String> hs = new HashSet<String>();
        hs.add("ciao");
        hs.add("hello");
        hs.add("hallo");
        hs.add("bonjour");

        Function<Set, Map> setToMap = s2 -> (Map) new HashMap().put(s2,s2);

        System.out.println(setToMap.apply(hs));
   }
}

For the above example, the expected result should be {B=bonjour, C=ciao, H=hello}.


Solution

  • I think this means that you have to add all the words of the Set in the Map following 2 rules

    • the key is the first letter in uppercase
    • the value is the word

    Function<Set<String>, Map<Character, String>> setToMap = aSet -> {
        Map<Character, String> map = new HashMap<>();
        for (String s : aSet ) {
            map.put(s.toUpperCase().charAt(0), s);
        }
        return map;
    };
    // or using Streams :
    Function<Set<String>, Map<Character, String>> setToMap = aSet  -> 
          aSet.stream().collect(Collectors.toMap(s -> s.toUpperCase().charAt(0), 
                                                 Function.identity(),
                                                 (oldK, newK) -> oldK)); // merging function in cas of duplicate key
    

    Tip: don't use raw types, but specify them as much as possible:

    • Function<Set,Map> becomes Function<Set<String>, Map<Character, String>>