从对象列表中收集值到映射表中。

huangapple go评论86阅读模式
英文:

Collect values from List of objects to Map

问题

我有一个类:

class Employee {
   private Integer id;
   private String name;
   //getters/setters
}

同时,我有一个包含员工的ArrayList:

List<Employee> employees = new ArrayList<>();

如何使用流提取id作为键,name作为值,放入HashMap中?

map.put(employee.getId(), employee.getName());

更新

如果我的字段中有自定义的列表呢?

class Employee {
   private List<Filter> filters;
   private String name;
   //getters/setters
}

class Filter {
   String name;
   String keyword;
   //getters/setters
}

我想将Filter中的name作为值,keyword作为键放入映射中。

英文:

I have class:

class Employee {
   private Integer id;
   private String name;
   //getters/setters
}

Also I've an Arraylist with employees:

List&lt;Employee&gt; employees = new Arraylist&lt;&gt;();

How can I extract id as a key and name as a value to HashMap (with streams)?

map.put(employee.getId(), employee.getName())

UPDATED

What if I've a custom Lists as fields?

class Employee {
   private List&lt;Filters&gt; filters;
   private String name;
   //getters/setters
}

class Filter {
   String name;
   String keyword;
   //getters/setters
}

And I want to put name (from Filter) as a value, and keyword as a key to map.

答案1

得分: 1

你可以使用流将其转换如下:

public Map<Integer, String> convertListToMap(List<Employee> list) {
    Map<Integer, String> map = list.stream()
      .collect(Collectors.toMap(Employee::getId, Employee::getName));
    return map;
}
英文:

You can convert using streams as below:

 public Map&lt;Integer, String&gt; convertListToMap(List&lt;Employee&gt; list) {
    Map&lt;Integer, String&gt; map = list.stream()
      .collect(Collectors.toMap(Employee::getId, Employee:: getName));
    return map;
}

答案2

得分: -2

&lt;!-- begin snippet: js hide: false console: true babel: false --&gt;

&lt;!-- language: lang-html --&gt;

    Map&lt;String,String&gt; map=Maps.newHashMap();
    employees.stream().forEach(-&gt;{
      map.put(i.getId,i.getName);
    });

&lt;!-- end snippet --&gt;
英文:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

Map&lt;String,String&gt; map=Maps.newHashMap();
employees.stream().forEach(-&gt;{
  map.put(i.getId,i.getName);
});

<!-- end snippet -->

huangapple
  • 本文由 发表于 2020年9月29日 20:02:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/64119211.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定