Stream Way to get index of first element matching boolean

前端 未结 6 1056
隐瞒了意图╮
隐瞒了意图╮ 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:33

    You can try StreamEx library made by Tagir Valeev. That library has a convenient #indexOf method.

    This is a simple example:

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

提交回复
热议问题