Collect to treemap java 8

Viewed 3478

I wanted to collect the result to a TreeMap<Integer,Double> by processing a TreeMap<Integer,ArrayList<String>>.

TreeMap<Integer,Double> result2 = units.entrySet().stream()
                                        .filter(v -> v.getValue().size()>3)
                                        .filter(v -> !v.getValue().get(1).isEmpty() && !v.getValue().get(2).isEmpty())
                                        .mapToDouble(v -> mult( v.getValue().get(1), v.getValue().get(2)))
                                        .collect();

Basically what I am doing is that I get the values from the ArrayList of Strings from the stream, and filter out the ones with no values and get a product of the 2nd and 3rd element by using mult function inside the lambda expression. Now I don't know how to collect to a TreeMap where the key is the key of the processed TreeMap called units and the value should be the product that I calculated in the mapToDouble.

NOTE: units is a TreeMap<Integer,ArrayList<String>>

1 Answers

You can collect the data to a TreeMap by using the overloaded version of toMap(keyMapper, valueMapper, mergeFunction, mapSupplier) method that allows you to specify which Map to create.

TreeMap<Integer,Double> result2 = units.entrySet().stream()
                    .filter(v -> v.getValue().size()>3)
                    .filter(v -> !v.getValue().get(1).isEmpty() && !v.getValue().get(2).isEmpty())
                    .collect(Collectors.toMap(
                            entry -> entry.getKey(),
                            entry-> mult( entry.getValue().get(1), entry.getValue().get(2)),
                            (entry1, entry2) -> entry1, // called if duplicate keys are there, I have return entry1 by default by you can modify it according to you
                            TreeMap::new
                    ));

you can refer this to look at overloads of toMap method. https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html

Related