1

I have the below code and I am using lamda expression to set the key and value pair of the hashMap to the list of Stats. I am new to stream API and I want to do it in stream API, can anyone help with this. Thanks.

    final List<Stats> values = new ArrayList<>();
        if (countMap != null) {
                    countMap.forEach((k, v) -> {
                        final Stats value = new Stats();
                        value.setType(k);
                        value.setCount(v);
                        final double percent = getPercentage(v, total.get());
                        value.setPercent(percent);
                        values.add(value);
                    });
                }

private double getPercentage(final double count, final double total) {
        final double percent = (count / (total * 1.0)) * 100;
        final BigDecimal bd = new BigDecimal(percent).setScale(2, RoundingMode.HALF_UP);
        return bd.doubleValue();
    }
Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
user10382836
  • 87
  • 1
  • 2
  • 5
  • 5
    this would be _a lot_ simpler if you could provide a constructor for `Stats` that would take a `k` and `v` (whatever those types are...) – Eugene Oct 17 '19 at 19:38
  • 1
    Possible duplicate of [How to convert a Map to Arraylist of Objects?](https://stackoverflow.com/questions/42694964/how-to-convert-a-map-to-arraylist-of-objects) – Michał Krzywański Oct 17 '19 at 19:52
  • Another [one](https://stackoverflow.com/questions/49030336/converting-mapstring-string-to-listobject-in-java8) and also [this](https://stackoverflow.com/questions/21233183/java-8-stream-mapk-v-to-listt) – Michał Krzywański Oct 17 '19 at 19:54

2 Answers2

4

You can simplify the code with an all argument constructor defined, to something like:

final List<Stats> values = countMap.entrySet().stream()
        .map(e -> new Stats(e.getKey(), e.getValue(), getPercentage(e.getValue(), total.get())))
        .collect(Collectors.toList());

where the constructor resolves to

new Stats(<type>, <count>, <percent>)

Note: Avoid assigning null value to a Map, instead initialize it as empty. The code with that additional check would look like:

final List<Stats> values = countMap != null ? countMap.entrySet().stream()
        .map(e -> new Stats(e.getKey(), e.getValue(), getPercentage(e.getValue(), total.get())))
        .collect(Collectors.toList()) : Collections.emptyList();
Naman
  • 27,789
  • 26
  • 218
  • 353
0

you can grab entrySet and iterate over it using streams