首页 > 解决方案 > 将对象流转换为地图

问题描述

我想将对象流转换为地图。键是对象本身,值是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()方法中的键(甚至值)。

标签: java

解决方案


您可以分两步完成:

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));
}

推荐阅读