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

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

问题描述

我有一个 List.我想使用特定用户名获取流中(第一个)用户的索引.我不想实际要求 User 成为某些描述的 User.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() 函数的类型来描述你正在寻找的属性;我宁愿有一些可以用于任意 Function

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 不是恒定时间操作,该解决方案可能会很耗时.

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

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