I have two lists
List<SampleClassOne> listOne;
List<SampleClassTwo> listTwo;
public class SampleClassOne{
private String myProperty;
private String myOtherProperty
//ommiting getters-setters
}
public class SampleClassTwo{
private String myProperty;
private String someOtherProperty
//ommiting getters-setters
}
I want do this
List<String> someOtherPropertyList;
for(SampleClassOne One : listOne) {
for(SampleClassTwo two : listTwo) {
if (one.getMyProperty().equals(two.getMyProperty())){
someOtherPropertyList.add(two.getSomeOtherProperty());
}
}
}
return someOtherPropertyList;
Can I do everything after the "I want do this" using Lambdas in an efficient way?
I recomend think about performance and write as following:
Collection<String> myPropertiesFromListOne = listOne.stream()
.map(SampleClassOne::getMyProperty)
.collect(Collectors.toSet()); // removes duplicated elements
List<String> someOtherPropertyList = listTwo.stream()
.filter(sampleClassTwo ->
myPropertiesFromListOne.contains(sampleClassTwo.getMyProperty())
)
.map(SampleClassTwo::getSomeOtherProperty)
.collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With