Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using java Lambda to join two list on a common attribute and collect another attribute

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?

like image 737
peztherez Avatar asked Mar 07 '23 23:03

peztherez


1 Answers

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());
like image 130
Beno Arakelyan Avatar answered Mar 10 '23 13:03

Beno Arakelyan