Reputation: 2069
I have a List of String, i need to iterate elements and create a new Object for each element in the list and add to a parent list, how do ido in Java 8 , this is what i tried so far:
List<CustomObject> parentList = new ArrayList<>();
List<String> emailList = fromSomeMethod();
emailList().stream().forEach(email -> parentList.add(new CustomObject(email)));
I am getting an error:
"variable used in lambda expression should be final or effectively final"
Any suggestions ? dont want to do it in the old school way, Thanks,
Upvotes: 0
Views: 2796
Reputation: 625
Use this:
static class CustomObject {
String email;
public CustomObject(String email) {
this.email = email;
}
}
private static void test4() {
List<CustomObject> parentList = new ArrayList<>();
List<String> emailList = Arrays.asList("[email protected]", "[email protected]");
emailList.stream()
.map(CustomObject::new)
.forEach(parentList::add);
}
Upvotes: 0
Reputation: 4509
Try like this You should have Parameterized Constructor
public class CustomObject {
private String email;
private boolean isFlag;
//Getter setter
public CustomObject(String email, boolean isFlag) {
this.email = email;
this.isFlag = isFlag;
}
public CustomObject(String email) {
this.email = email;
}
}
List<CustomObject> parentList = emailList.stream().map(CustomObject::new).collect(Collectors.toList());
Upvotes: 0
Reputation: 120858
List<CustomObject> parentList = emailList().stream()
.map(CustomObject::new)
.collect(Collectors.toList());
No need to complicated things, just map
that and collect to a new List
Upvotes: 1