We Are Going To Discuss About Stream Way to get index of first element matching boolean. So lets Start this Java Article.
Stream Way to get index of first element matching boolean
- Stream Way to get index of first element matching boolean
Occasionally there is no pythonic
zipWithIndex
in java. So I came across something like that:OptionalInt indexOpt = IntStream.range(0, users.size()) .filter(i -> searchName.equals(users.get(i))) .findFirst();
- Stream Way to get index of first element matching boolean
Occasionally there is no pythonic
zipWithIndex
in java. So I came across something like that:OptionalInt indexOpt = IntStream.range(0, users.size()) .filter(i -> searchName.equals(users.get(i))) .findFirst();
Solution 1
Occasionally there is no pythonic zipWithIndex
in java. So I came across something like that:
OptionalInt indexOpt = IntStream.range(0, users.size())
.filter(i -> searchName.equals(users.get(i)))
.findFirst();
Alternatively you can use zipWithIndex
from protonpack library
Note
That solution may be time-consuming if users.get is not constant time operation.
Original Author vsminkov Of This Content
Solution 2
Try This:
IntStream.range(0, users.size())
.filter(userInd-> users.get(userInd).getName().equals(username))
.findFirst()
.getAsInt();
Original Author AmanSinghal Of This Content
Solution 3
Using Guava library: int index =
Iterables.indexOf(users, u -> searchName.equals(u.getName()))
Original Author karmakaze Of This Content
Solution 4
You can try StreamEx library made by Tagir Valeev. That library has a convenient #indexOf method.
This is a simple example:
List<User> users = asList(new User("Vas"), new User("Innokenty"), new User("WAT"));
long index = StreamEx.of(users)
.indexOf(user -> user.name.equals("Innokenty"))
.getAsLong();
System.out.println(index);
Original Author SerCe Of This Content
Conclusion
So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.