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:
Create a variable of type
Function<Set, Map>
that receives aSet
and creates aHashMap
using lambda expressionsPut words in the map, using as key the uppercase first letter of that word
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}
.
I think this means that you have to add all the
words
of theSet
in theMap
following 2 rulesTip: don't use raw types, but specify them as much as possible:
Function<Set,Map>
becomesFunction<Set<String>, Map<Character, String>>