Java 8: convert List<V> to Map<K, V> using Stream API
Hello everyone! I started learning Java 8 and came across a problem that seems simple, but I can't solve it. I have a list of `Person` objects:
```java
public class Person {
private int id;
private String name;
private int age;
// constructor, getters and setters
}
```
I need to convert `List` to `Map`, where the key will be `id` and the value will be the `Person` object itself. Before Java 8, I did this using a loop:
```java
List list = Arrays.asList(
new Person(1, "Alice", 30),
new Person(2, "Bob", 25),
new Person(3, "Charlie", 35)
);
Map map = new HashMap<>();
for (Person p : list) {
map.put(p.getId(), p);
}
```
But I heard that in Java 8 this can be done more elegantly using la
No answers yet.
Log in to leave an answer