0

I am trying to make a Hashmap out of a List of Objects[] but I am unable to do so. Below is the code that I have written:

List<Object[]> adjustments =  query.getResultList();
Map<Integer, BigDecimal> dpaMap = adjustments.stream().collect(Collectors.toMap(a -> (Integer)a[0], a -> (BigDecimal)a[1]));

I know that only two fields are returning from the query they have the same Type as mentioned in Map, but its not working. Please guide me in this regard.

Thanks In Advance.

Sartorius
  • 499
  • 5
  • 12
Muhammad Umer
  • 363
  • 2
  • 8
  • 19
  • 1
    Possible duplicate of [Java: How to convert List to Map](http://stackoverflow.com/questions/4138364/java-how-to-convert-list-to-map) – Sanka Oct 27 '16 at 09:28
  • https://www.mkyong.com/java8/java-8-convert-list-to-map/ – Sanka Oct 27 '16 at 09:29
  • Your code works fine to me (when the `Object[]` arrays contain what you say they do). I tried : `List adjustments = new ArrayList(); adjustments.add (new Object[] {Integer.valueOf (5),new BigDecimal(4)}); adjustments.add (new Object[] {Integer.valueOf (55),new BigDecimal(48)}); Map dpaMap = adjustments.stream().collect(Collectors.toMap(a -> (Integer)a[0], a -> (BigDecimal)a[1]));` – Eran Oct 27 '16 at 09:30
  • @Sanka no, I want to use Java streams. Thanks – Muhammad Umer Oct 27 '16 at 09:30
  • @Eran When I am debugging the code, it doesn't recognize a[0] and a[1] and when the 2nd line executes, it throws an exception – Muhammad Umer Oct 27 '16 at 09:32
  • @MuhammadUmer What exception? – Eran Oct 27 '16 at 09:32

1 Answers1

6

So it seems that it was working fine, the column in the DB was returning Float so just had to cast it to BigDecimal

Map<Integer, BigDecimal> dpaMap = adjustments.stream().collect(Collectors.toMap(a -> (Integer)a[0], a -> BigDecimal.valueOf((Float) a[1])));

Thanks a lot people for your help.

Muhammad Umer
  • 363
  • 2
  • 8
  • 19