Collect the result with only a stream (without external loop use)


Collect the result with only a stream (without external loop use)



Is there a way to do the following code only with lambdas ?


// translate someList1 to someList3
// .. get sublist
List<String> someList2 = someList1.stream()
.map(i -> i.getField())
.collect(Collectors.toList());
// .. create new (target) list
List<SomeClass> someList3 = new ArrayList<>();
for (String item : someList2) {
SomeClass someObj = new SomeClass();
someObj.setField(item);
someList3.add(someObj);
}




3 Answers
3



Just one collect is required :


List<SomeClass> someList2 =
someList1.stream()
.map(i -> {
SomeClass someObj = new SomeClass();
someObj.setField(i.getField());
return someObj;
}
)
.collect(Collectors.toList());



But note that with a constructor in SomeClass that accepts the value of getField(), it would be really more neat :


SomeClass


getField()


List<SomeClass> someList2 =
someList1.stream()
.map(i-> new SomeClass(i.getField())
.collect(Collectors.toList());



Or by spliting the map() operation in two distinct transformations, you can use method references, which improves the readability :


map()


List<SomeClass> someList2 =
someList1.stream()
.map(OneClass::getField)
.map(SomeClass::new)
.collect(Collectors.toList());



You can achieve that with a multiline lambda and another map operation:


List<SomeClass> someList3 = someList1.stream()
.map(i -> i.getField())
.map(f -> {
SomeClass someObj = new SomeClass();
someObj.setField(f);
return someObj;
})
.collect(Collectors.toList());



No need to map it to a String then back to SomeClass, do it in the one map:


map


String


SomeClass


List<SomeClass> someList2 = list.stream()
.map(i -> new SomeClass(i.getField())) //in case you have such constructor
.collect(Collectors.toList());






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Opening a url is failing in Swift

Export result set on Dbeaver to CSV