I want to translate a List of objects into a Map using Java 8\'s streams and lambdas.
This is how I would write it in Java 7 and below.
private Map&l
I will write how to convert list to map using generics and inversion of control. Just universal method!
Maybe we have list of Integers or list of objects. So the question is the following: what should be key of the map?
create interface
public interface KeyFinder {
K getKey(E e);
}
now using inversion of control:
static Map listToMap(List list, KeyFinder finder) {
return list.stream().collect(Collectors.toMap(e -> finder.getKey(e) , e -> e));
}
For example, if we have objects of book , this class is to choose key for the map
public class BookKeyFinder implements KeyFinder {
@Override
public Long getKey(Book e) {
return e.getPrice()
}
}