Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream Way to get index of first element matching boolean

I have a List<Users>. I want to get the index of the (first) user in the stream with a particular username. I don't want to actually require the User to be .equals() to some described User, just to have the same username.

I can think of ugly ways to do this (iterate and count), but it feels like there should be a nice way to do this, probably by using Streams. So far the best I have is:

int index = users.stream()     .map(user -> user.getName())     .collect(Collectors.toList())     .indexOf(username); 

Which isn't the worst code I've ever written, but it's not great. It's also not that flexible, as it relies on there being a mapping function to a type with a .equals() function that describes the property you're looking for; I'd much rather have something that could work for arbitrary Function<T, Boolean>

Anyone know how?

like image 408
Edward Peters Avatar asked Aug 15 '16 21:08

Edward Peters


People also ask

How do you find the index of an element in a stream?

In order to find the index of an element Stream package provides utility, IntStream. Using the length of an array we can get an IntStream of array indices from 0 to n-1, where n is the length of an array. Below is the implementation of Stream API approach.

Which method in stream API is used to create a stream from first element to last element and the result has to include the last element in the created stream?

To get the last element, you can use the skip() method along with count() method. This returns a stream after removing first size()-1 elements, which results in single element stream. This method is followed by findFirst() method, which return the first element which is actually a last element of original stream.

How do you loop through each element in a stream?

Java Stream forEach() method is used to iterate over all the elements of the given Stream and to perform an Consumer action on each element of the Stream.


2 Answers

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.

like image 71
vsminkov Avatar answered Sep 24 '22 03:09

vsminkov


Try This:

IntStream.range(0, users.size())     .filter(userInd-> users.get(userInd).getName().equals(username))     .findFirst()     .getAsInt(); 
like image 25
AmanSinghal Avatar answered Sep 26 '22 03:09

AmanSinghal