Suppose your A
class has a getX()
method that gives Long
and a getY()
method that gives BigDecimal
. With this, you can use method Collectors.toMap
:
List<A> suaLista = ...;
Map<Long, BigDecimal> map = suaLista.stream().collect(Collectors.toMap(A::getX, A::getY);
Please note this detail of method documentation:
If the mapped keys contain duplicates (according to Object.equals(Object)
), an IllegalStateException
is thrown when the collection operation is performed.
Translating:
If the mapped keys contain duplicates (according to Object.equals(Object)
), a IllegalStateException
is posted when the collection operation is performed.
This means that this exception will be thrown if your list has at least two objects with the same% s of% s.
If you want to accept the duplicates, and keep only one of them, the same documentation says the following:
If the mapped keys might have duplicates, use Long
instead.
Translating:
If mapped keys can have duplicates, use toMap(Function, Function, BinaryOperator)
instead.
And to keep only the first key, it would be this:
List<A> suaLista = ...;
Map<Long, BigDecimal> map = suaLista.stream()
.collect(Collectors.toMap(A::getX, A::getY, (p, q) -> p);
This toMap(Function, Function, BinaryOperator)
is the (p, q) -> p
that receives two values and returns the first.