1

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.

6
  • 1
    Possible duplicate of Java: How to convert List to Map Commented Oct 27, 2016 at 9:28
  • mkyong.com/java8/java-8-convert-list-to-map Commented Oct 27, 2016 at 9:29
  • Your code works fine to me (when the Object[] arrays contain what you say they do). I tried : List<Object[]> adjustments = new ArrayList<Object[]>(); adjustments.add (new Object[] {Integer.valueOf (5),new BigDecimal(4)}); adjustments.add (new Object[] {Integer.valueOf (55),new BigDecimal(48)}); Map<Integer, BigDecimal> dpaMap = adjustments.stream().collect(Collectors.toMap(a -> (Integer)a[0], a -> (BigDecimal)a[1])); Commented Oct 27, 2016 at 9:30
  • @Sanka no, I want to use Java streams. Thanks Commented Oct 27, 2016 at 9: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 Commented Oct 27, 2016 at 9:32

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.