Stream Way to get index of first element matching boolean

java-stream get current index
java 8 foreach get current index
java find index of element in array
java find index of element in list
java get index of item in arraylist
java find first match in list
java stream get nth element
java streams index of element

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?

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.

Find index of an element in given array in Java, In this post, we will see how to find the index of an element in a primitive or object array in Java. The solution should either return the index of first occurrence of the required element, or -1 if the element is not present Java 8: Stream Longs for long, Doubles for double, Floats for float, Booleans for boolean, and so on. 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, j

Try This:

IntStream.range(0, users.size())
    .filter(userInd-> users.get(userInd).getName().equals(username))
    .findFirst()
    .getAsInt();

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� In boolean indexing, we use a boolean vector to filter the data. Boolean indexing is a type of indexing which uses actual values of the data in the DataFrame. In boolean indexing, we can filter a data in four ways – Accessing a DataFrame with a boolean index; Applying a boolean mask to a dataframe; Masking data based on column value

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);

How to Find an Element in a List with Java, Have a look at some quick ways to find an element in a list in Java. The indexOf method; An ad-hoc for loop, and; The Stream API boolean contains( Object element) index of the first occurrence of the specified element in the given list, To find an element matching specific criteria in a given list, we:. boolean anyMatch(Predicate<? super T> predicate) Where, T is the type of the input to the predicate and the function returns true if any elements of the stream match the provided predicate, otherwise false. Note : If the stream is empty then false is returned and the predicate is not evaluated.

A solution without any external library

AtomicInteger i = new AtomicInteger(); // any mutable integer wrapper
int index = users.stream()
    .peek(v -> i.incrementAndGet())
    .anyMatch(user -> user.getName().equals(username)) ? // your predicate
    i.get() - 1 : -1;

peek increment index i while predicate is false hence when predicate is true i is 1 more than matched predicate => i.get() -1

How to Iterate Over a Stream With Indices, Learn several ways of iterating over Java 8 Streams using indices. this approach. Simply put, we want to get an array of Strings and only select even indexed elements: ? First, you need to add it to your pom.xml: ? Given a boolean list such as [True, False, False, True, False, True], what is the quickest way to get a list/tuple containing the indexes (starting from 1, not zero-indexed) of the Truthy elements

Using Guava library: int index = Iterables.indexOf(users, u -> searchName.equals(u.getName()))

Java 8 Stream findFirst() and filter() Example, You can use the Stream class along with filter() and findFirst() methods to find out an element upon a Predicate, a functional interface for defining a condition which returns a boolean. How to find the first element from a Stream with filter. anyMatch () method takes a predicate, an expression or a function which returns a boolean value. In our case, the predicate compares each element n in the stream to toFind and returns true or false. If any of the element n returns true, found is set to true as well. Example 3: Check if array contains a given value for non-primitive types

Stream anyMatch() in Java with examples, Stream anyMatch(Predicate predicate) returns whether any elements of this stream true if any elements of the stream match the provided predicate, otherwise false. examples to understand the implementation of the function in a better way. function to check whether any element in list having UpperCase at 1st index. It returns true if the element is matched, else returns false. Example. In this example, we have created two ArrayList firstList and secondList of String type. We have compared these ArrayList using contains() method. If the elements of firstList match with the elements of the secondList, it return Yes and stores this value into thirdList.

Part 2: Processing Data with Java SE 8 Streams, In the first part of this series, you saw that streams let you process collections with database-like operations. Let's get started and explore how the flatMap and collect operations work. (that is, a function that returns a boolean ) and groups the elements of a stream according to whether or not they match that predicate. Java examples to check if an Array (String or Primitive type) contains a certain values, updated with Java 8 stream APIs. 1. String Arrays. 1.1 Check if a String Array contains a certain value “A”.

Stream (Java SE 11 & JDK 11 ), Streams have a BaseStream.close() method and implement AutoCloseable . Returns whether all elements of this stream match the provided predicate. stream whose elements are all the elements of the first stream followed by all the elements of boolean foundAny = false; T result = null; for (T element : this stream) { if� First create two ArrayList and add values of list. Convert the ArrayList to Stream using stream () method. Set the filter condition to be distinct using contains () method. Collect the filtered values as List using collect () method.

Comments
  • Why is "iterate" ugly?
  • Streams and indexing don't mix well. You're usually better off falling back to an old-style loop at that point.
  • @Andreas The thing I like about streams is the separation of the collection-related logic from the specific thing being asked. In this case, there are a ton of different questions that could be asked that only vary from the core Function<T, Boolean>, so it feels like there should be a way to handle that that abstracts it from the general collection logic.
  • What prevents you from using a Function<T, Boolean> in an if statement inside a for loop? Why do you want to use Function<T, Boolean> when you have Predicate<T>?
  • @Andreas Because there you're manually describing all of the structure-related code, rather than having that compartmentalized. To the other question, I just forgot that Predicate was a thing.
  • That works. I could also skip the pair by just looking up the user with the given index in the filter operation... not sure if that's better or worse.
  • @EdwardPeters It's definitely better. At least that eliminates additional memory traffic
  • @vsminkov, You should be careful here. Nobody said that the list has O(1) access.
  • @SerCe fair enough. the other option is to implement custom spliterator like protonpack does. I'll put a note
  • That gets me the user, but not the index
  • Agree with you, can you please help me with suggestions to handle that use case here.
  • Instead of get(), use orElse(-1), as other index-of operations do.
  • but the code will crash here users.get(userInd). getName() if returned user is null. Do stream API takes care of NullPointerexception also ?
  • @AmanSinghal IMO, you shouldn't have null values in lists, but empty lists or lists that are missing a requested name make sense. If you get an NPE because someone put a null value into a list, that's their fault