Stream Way获取匹配boolean的第一个元素的索引 [英] Stream Way to get index of first element matching boolean

查看:80
本文介绍了Stream Way获取匹配boolean的第一个元素的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有列表< Users> 。我想用特定的用户名获取流中(第一个)用户的索引。我不想实际要求用户 .equals()描述用户,只是为了拥有相同的用户名。

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.

我可以想到这样做的丑陋方法(迭代和计数),但感觉应该有一个很好的方法来做到这一点,可能是通过使用Streams。到目前为止,我所拥有的最好的是:

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

这不是我写过的最糟糕的代码,但它并不好。它也不是那么灵活,因为它依赖于一个带有 .equals()函数的类型的映射函数来描述你正在寻找的属性;我宁愿有一些可以用于任意功能< T,布尔>

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?

推荐答案

偶尔在java中没有pythonic zipWithIndex 。所以我遇到了类似的东西:

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

或者你可以从 zipWithIndex href =https://github.com/poetix/protonpack =noreferrer> protonpack 库

Alternatively you can use zipWithIndex from protonpack library

注意

如果users.get不是常量时间操作,那么该解决方案可能会非常耗时。

这篇关于Stream Way获取匹配boolean的第一个元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆