I want to create a cloned list. I am using the below code snippet, but my IDE is showing a compilation error as "Cannot resolve constructor" even though MyClass
has a default constructor.
List<MyClass> clonedList =
myClassList.stream().map(MyClass::new).collect(Collectors.toList());
I am new to streams, please help me if my syntax is wrong.
MyClass::new
will only work in this context if your class has a constructor that takes a single parameter whose type is the type of the elements of the Stream
. Parameter-less constructor won't work.
myClassList.stream().map(MyClass::new)...
behaves as
myClassList.stream().map(e -> new MyClass(e))...
Since myClassList
is a list of MyClass
instances, this means a constructor of the following signature will be required in order for the method reference to work - MyClass (MyClass other)
.
You can still use the parameter-less constructor with the following lambda expression:
myClassList.stream().map(e -> new MyClass())...
Of course, that makes little sense, since it ignores the original elements of the Stream
.
Since your goal is to clone the List
, you need a copy constructor:
public MyClass (MyClass other) {
// copy the properties of other to this instance
}