1

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));
    }
}
Turamarth
  • 2,282
  • 4
  • 25
  • 31
Giacomo Brunetta
  • 1,409
  • 3
  • 18
  • 38
  • 3
    `Function, List> setToList = s -> new ArrayList(s);` – Eugene May 17 '18 at 13:28
  • @Eugene it works fine! Thank you! Please, answer and I will evaluate your response! – Giacomo Brunetta May 17 '18 at 13:30
  • Don't understand why this question is getting downvoted. Yes, it's homework, but the OP has shown what he's tried so far. – Morgan May 17 '18 at 13:32
  • @Morgan yeah, me too!! I don't understand that! Of course, it is not a school homework! I'm just try to understand how these things works and I follow a e-learning course with some practicse, that's all! I wrote that hust to understand – Giacomo Brunetta May 17 '18 at 13:34

1 Answers1

2

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

Eugene
  • 117,005
  • 15
  • 201
  • 306