Let’s assume your class A
have a method getX()
that gives the value Long
and a method getY()
that gives the BigDecimal
. With this, you can use the method Collectors.toMap
:
List<A> suaLista = ...;
Map<Long, BigDecimal> map = suaLista.stream().collect(Collectors.toMap(A::getX, A::getY);
It is worth mentioning this detail of the method documentation:
If the Mapped Keys contain Uplicates (According to Object.equals(Object)
), an IllegalStateException
is thrown when the Collection Operation is performed.
Translating:
If the mapped keys contain duplicates (according to the Object.equals(Object)
), one IllegalStateException
is launched when the collection operation is performed.
Which means this exception will be thrown if your list has at least two objects with the same Long
s.
If you want to accept duplicates, and take only one of them, that same documentation says the following:
If the Mapped Keys Might have Uplicates, use toMap(Function, Function, BinaryOperator)
Instead.
Translating:
If mapped keys can have duplicates, use toMap(Function, Function, BinaryOperator)
instead.
And to keep only the first key, then that would be:
List<A> suaLista = ...;
Map<Long, BigDecimal> map = suaLista.stream()
.collect(Collectors.toMap(A::getX, A::getY, (p, q) -> p);
That one (p, q) -> p
is the BinaryOperator
that takes two values and returns the first.
The name has now escaped me, but if I am not mistaken, there is a Colection that does not allow repetition within it. On this link is someone who has achieved something similar to what you want (in English) https://stackoverflow.com/questions/14476548/which-data-structure-to-use-for-keeping-a-list-unique-with-insertion-order-intac
– user111413
as you have 2 different types within the same list?
– Pedro
Does this list have exactly two items? Or does it have
Long
s andBigDecimal
s alternating?– Victor Stafusa
Guys, I’m sorry to ask...actually the list is for an object and this one has 2 attributes: Long and Bigdecimal.
– Roknauta