英文:
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<Employee> employees = new Arraylist<>();
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<Filters> 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<Integer, String> convertListToMap(List<Employee> list) {
Map<Integer, String> map = list.stream()
.collect(Collectors.toMap(Employee::getId, Employee:: getName));
return map;
}
答案2
得分: -2
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
Map<String,String> map=Maps.newHashMap();
employees.stream().forEach(->{
map.put(i.getId,i.getName);
});
<!-- end snippet -->
英文:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
Map<String,String> map=Maps.newHashMap();
employees.stream().forEach(->{
map.put(i.getId,i.getName);
});
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论