zond
zond

Reputation: 1480

java comparing properties of list elements , like list.contains(..) but by properties

I have two lists

class FirstElement {
       private int id;
       private String name;
}

class SecondElement {
       private int id;
       private String someString;
}

List<FirstElement> listF = getListOfSomeElements1();
List<SecondElement> listS = getListOfSomeElements2();

I need to find element in listF<FirstElement> if properties name=someString

If I need to find by corresponding of elements, i use for example:

if(listF.contains(listS.get(1))){...}

I use own method

boolean compareProperties(List<FirstElement> firstList, SecondElement secondElement){
 for(FirstElement firstElement:firstList){
        if (firstElement.getName().equals(secondElement.getSomestring)){
            return true;
        }
    }
    return false;
} 

how to remove my method with Stream?

Upvotes: 2

Views: 53

Answers (2)

Ousmane D.
Ousmane D.

Reputation: 56433

If you want to convert your current method into a stream version then you can use anyMatch.

boolean exists = 
           listF.stream()
                .anyMatch(e -> e.getName().equals(secondElement.getSomestring));

If you want to find the first element that satisfies the provided criteria then you can do:

Optional<FirstElement> firstElement = 
         listF.stream()
              .filter(e -> e.getName().equals(secondElement.getSomestring))
              .findFirst();

There are various ways to unwrap an Optional<T> which can be found here.

Upvotes: 1

Claudiu Guja
Claudiu Guja

Reputation: 350

You can filter the stream by the field that you need

Upvotes: 0

Related Questions