-1

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.

takotsubo
  • 666
  • 6
  • 18

2 Answers2

1

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;
}
Umesh Sanwal
  • 681
  • 4
  • 13
-2

Map<String,String> map=Maps.newHashMap();
employees.stream().forEach(->{
  map.put(i.getId,i.getName);
});
GuoZG
  • 1