Test Case Update

This commit is contained in:
Niket Agrawal 2023-10-31 18:11:34 +05:30
parent 63b435c097
commit 2f34022ded
1 changed files with 9 additions and 3 deletions

View File

@ -3,6 +3,7 @@ package com.baeldung.streams.firstmatchingelement;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List; import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream; import java.util.stream.IntStream;
import org.apache.commons.collections4.IterableUtils; import org.apache.commons.collections4.IterableUtils;
@ -17,12 +18,17 @@ public class FirstMatchingElementUnitTest {
private String searchName = "John"; private String searchName = "John";
@Test @Test
public void whenUsingIndexOf_thenFindFirstMatchingUserIndex() { public void whenUsingStream_thenFindFirstMatchingUserIndex() {
AtomicInteger counter = new AtomicInteger(-1);
int index = userList.stream() int index = userList.stream()
.filter(user -> searchName.equals(user.getUserName())) .filter(user -> {
.mapToInt(user -> userList.indexOf(user)) counter.getAndIncrement();
return searchName.equals(user.getUserName());
})
.map(user -> counter.get())
.findFirst() .findFirst()
.orElse(-1); .orElse(-1);
assertEquals(1, index); assertEquals(1, index);
} }