Stream Way to get index of first element matching boolean

前端 未结 6 1055
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 09:12

I have a List. 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 Us

6条回答
  •  醉话见心
    2020-12-01 09:37

    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

提交回复
热议问题