user1311432
user1311432

Reputation: 64

append values to a HashMap <String , ArraList<Object>>

I am trying to create a simple HashMap , which will have a String as a key , and for each key there's an ArrayList of Objects .

The problem with the solution I came up with is at the end of the loop , I get only one value (Object ) in the ArrayList ...

I tried using the MultiValueMap in Apache Commons but my IDE protests , it says it is deprecated

//filter products by supplier
            for(String nume:SuppliersNames){

                ArrayList<Order.Product> gol = new ArrayList<>();
                SuppliersMap.put(nume,gol);

                //we make a copy of the products collection so we can iterate it and filter elements by supplier

                ArrayList<Orders.Order.Product> interm = new ArrayList<Orders.Order.Product>(products);

                Iterator<Orders.Order.Product> iter = interm.iterator();

                while (iter.hasNext()){

                    Orders.Order.Product curent = iter.next();

                    if(curent.getSupplier()== nume){

                        SuppliersMap.get(nume).add(curent);
                    }
                }
            }

Upvotes: 0

Views: 817

Answers (1)

dpr
dpr

Reputation: 10972

As mentioned in the comments the problem is very likely the check curent.getSupplier() == nume. You are comparing for identity here and this is probably not what you want. Try changing this to curent.getSupplier().equals(nume) and see what happens.

Furthermore there is no need to create a local copy of the products collection as you are not modifying this collection in the posted snippet.

Using Java8 streams your code could be changed to this:

for (String name : suppliersNames) {
    List<Product> gol = products.stream().filter(p -> p.getSupplier().equals(name))
            .collect(Collectors.toList());
    suppliersNames.put(name, gol);
}

Upvotes: 2

Related Questions