Unary Functional Interface with Lambda in Java 8

233 views Asked by At

I'm studying for Java 8 Lambda and Unary Functional Interface. I have a practice assignment about "Function" class, which the following text:
1) Create a class called "FunctionTest" with a main method
2) Create a Function variable and call it as "setToList"
3) Assign to setToList a lambda expression in which taken a Set it creates an Arraylist and it adds all the elements of the Set
4) Create an HashSet and add the following world: "Ciao", "Hello", "Hallo", "Bonjour"
5) Call the lamda expression and view the result

I trying in the following way, but it doesn't work. In particular, I think that I wrong thw 3) step. I need to understand how to make that step

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Function;

public class FunctionTest {

    public static void main(String[] args) {

        Function<Set, List> setToList = s -> new ArrayList<Set>();
        HashSet<String> hs = new HashSet<String>();
        hs.add("ciao");
        hs.add("hello");
        hs.add("hallo");
        hs.add("bonjour");
        System.out.println(setToList.apply(hs));
    }
}
1

There are 1 answers

0
Eugene On BEST ANSWER

You have to define it a little different:

Function<Set<String>, List<String>> setToList = s -> new ArrayList<String>(s);

Or better use a method reference:

Function<Set<String>, List<String>> setToList = ArrayList::new;

Don't use raw types and use the ArrayList constructor that takes a Collection as input