java - 将对象流转换为地图
问题描述
我想将对象流转换为地图。键是对象本身,值是Function.identity()
。我的目标是为每个人创建一个增量索引。
public class Person {
private String firstName;
private String lastName;
}
/* Expected Result
Key:[Person1], value:1
Key:[Person2], value:2
Key:[Person3], value:3
*/
public Map<Person, Integer> getMapOfPersons(Stream<Person> persons) {
return persons.filter(p -> "John".equalIgnoreCase(p.getFirstName)
.collect(Collectors.toMap(Person, Function.identity()));
}
我的问题是,在应用 之后.filter()
,我不能将我的对象作为.toMap()
方法中的键(甚至值)。
解决方案
您可以分两步完成:
public Map<Person, Integer> getMapOfPersons(Stream<Person> persons) {
List<Person> filterd = persons.filter(p -> "John".equalIgnoreCase(p.getFirstName))
.collect(Collectors.toList());
return IntStream.range(0, filterd.size())
.boxed()
.collect(Collectors.toMap(filterd::get, i -> i + 1));
}
推荐阅读
- puppet - 如何在 puppet 3.7 中推迟“文件”函数的执行
- c# - Rtf 图片未显示在 Gmail 中
- cluster-computing - 具有单个公共 IP 的 Apache Ignite 集群
- microsoft-cognitive - Azure Bing 语音 API 和语音转文本
- javascript - 在javascript中改变运动方向时旋转css精灵
- java - Java enum - 如何在枚举的构造函数中调用另一个枚举值
- php - 如何让我的属性过滤器工作?
- csv - 为什么 redshift 在 stl_load_commits 中没有 csv 文件的条目?
- javascript - 您已在此页面上多次包含 Google Maps JavaScript API。这可能会导致意外错误。使用 $.getScript() 调用时
- ms-access - 可变输入掩码