Stream Way to get index of first element matching boolean(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 不是恒定时间操作,该解决方案可能会很耗时.
这篇关于Stream方式获取第一个元素匹配布尔值的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Stream方式获取第一个元素匹配布尔值的索引
基础教程推荐
- 存储 20 位数字的数据类型 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
