Stream方式获取第一个元素匹配布尔值的索引
我有一个List<Users>
.我想使用特定用户名获取流中(第一个)用户的索引.我不想实际上要求 User
是 .equals()
到一些描述的 User
,只是为了拥有相同的用户名.
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()
函数;我宁愿有一些可以用于任意 Function<T, Boolean>
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>
有人知道怎么做吗?
推荐答案
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();
您也可以使用 protonpack 库中的 zipWithIndex
Alternatively you can use zipWithIndex
from protonpack library
注意
如果 users.get 不是恒定时间操作,该解决方案可能会很耗时.
相关文章