如何使用Java 8流将列表的元素映射到它们的索引?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了如何使用Java 8流将列表的元素映射到它们的索引?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1470字,纯文字阅读大概需要3分钟。
内容图文
![如何使用Java 8流将列表的元素映射到它们的索引?](/upload/InfoBanner/zyjiaocheng/708/96e4c11efee245eeaeed48d1bb7c95f8.jpg)
有了一个字符串列表,我需要构建一个有效对的列表(字符串,它在列表中的位置).目前我有使用google集合的代码:
public Robots(List<String> names) {
ImmutableList.Builder<Robot> builder = ImmutableList.builder();
for (int i = 0; i < names.size(); i++) {
builder.add(new Robot(i, names.get(i)));
}
this.list = builder.build();
}
我想用Java 8流做到这一点.如果没有索引,我可以这样做:
public Robots(List<String> names) {
this.list = names.stream()
.map(Robot::new) // no index here
.collect(collectingAndThen(
Collectors.toList(),
Collections::unmodifiableList
));
}
要获得索引,我必须做这样的事情:
public Robots(List<String> names) {
AtomicInteger integer = new AtomicInteger(0);
this.list = names.stream()
.map(string -> new Robot(integer.getAndIncrement(), string))
.collect(collectingAndThen(
Collectors.toList(),
Collections::unmodifiableList
));
}
但是,文档说映射函数应该是无状态的,但AtomicInteger实际上是它的状态.
有没有办法将顺序流的元素映射到它们在流中的位置?
解决方法:
你可以这样做:
public Robots(List<String> names) {
this.list = IntStream.range(0, names.size())
.mapToObj(i -> new Robot(i, names.get(i)))
.collect(collectingAndThen(toList(), Collections::unmodifiableList));
}
但是,根据列表的底层实现,它可能效率不高.你可以从IntStream中获取一个迭代器;然后在mapToObj中调用next().
作为替代方案,proton-pack库为流定义了zipWithIndex功能:
this.list = StreamUtils.zipWithIndex(names.stream())
.map(i -> new Robot(i.getIndex(), i.getValue()))
.collect(collectingAndThen(toList(), Collections::unmodifiableList));
内容总结
以上是互联网集市为您收集整理的如何使用Java 8流将列表的元素映射到它们的索引?全部内容,希望文章能够帮你解决如何使用Java 8流将列表的元素映射到它们的索引?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。