'Convert for loop with a return statement to stream and filter lambda statement [duplicate]
How can I convert the below for loop with return statement to a lambda expression or stream with filter.
for(PhysicianData d : physicianDataList)
{
if(d.getPhysicianName().equals(physicianName))
{
return true;
}
}
Solution 1:[1]
Use anyMatch()
boolean result = physicianDataList.stream()
.map(PhysicianData::getPhysicianName) // Stream of names
.filter(Objects::nonNull) //Skip nulls
.anyMatch(name -> name.equals(physicianName));
Solution 2:[2]
Since you're looking for anything that matches the name equality check (anything being the operative word), I suggest having a look at the Stream::anyMatch() method, as well as its other counterparts of Stream::allMatch() and Stream::noneMatch(). The above code can be rewritten as:
boolean result = physicianDataList
.stream()
.anyMatch(physicianData -> physicianData.getPhysicianName().equals(physicianName);
Solution 3:[3]
Use it:
class PhysicianData {
String physicianName;
public void setPhysicianName(final String physicianName) {
this.physicianName = physicianName;
}
public String getPhysicianName() {
return physicianName;
}
}
@Test
void test() {
PhysicianData one = new PhysicianData();
one.setPhysicianName("A");
PhysicianData two = new PhysicianData();
two.setPhysicianName("B");
List<PhysicianData> physicianDataList = List.of(one, two);
assertEquals(forMethod("A", physicianDataList), streamMethode("A", physicianDataList));
}
private boolean forMethod(final String physicianName, final List<PhysicianData> physicianDataList) {
for (PhysicianData d : physicianDataList) {
if (d.getPhysicianName().equals(physicianName)) {
return true;
}
}
return false;
}
private boolean streamMethode(final String physicianName, final List<PhysicianData> physicianDataList) {
return physicianDataList.stream().anyMatch(x-> x.getPhysicianName().equals(physicianName));
}
Solution 4:[4]
Try using anyMatch() that takes a predicate as an argument
boolean isFound = physicianDataList.stream()
.anyMatch(d -> d.getPhysicianName().equals(physicianName));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Ramen Dev |
| Solution 3 | Maxim Bezmen |
| Solution 4 | Bentaye |
