Hwo ca I use optional on map merge?

Sep 16, 2022
Reaction score
Here is my code so far I was able to merge three maps but I need to use an optional counter from a pojo.
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class mapMerge {
public static void main(String[] args) {

Map<String, Integer> branch1 = new HashMap<>();
branch1.put("Marvin", 3);
branch1.put("Aldrin", 2);
branch1.put("John", 5);
branch1.put("Roland", 4);

Map<String, Integer> branch2 = new HashMap<>();
branch2.put("Marvin", 9);
branch2.put("Roland", 8);

Map<String, Integer> branch3 = new HashMap<>();
branch3.put("John", 3);
branch3.put("Roland", 4);

Map<String, Integer> result = Stream.of(branch1, branch2, branch3).flatMap(m -> m.entrySet().stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (value1, value2) -> value1 + value2));




Here is the pojo;
import java.util.Optional;

public class UserStats {

Long visitCount = null;

Optional<Long> getVisitCount() {
return Optional.ofNullable(this.visitCount);

void setVisitCount(Long visitCount) {
this.visitCount = visitCount;

And here is the function I need to use;

import java.util.Map;

class VisitCounter {

Map<Long, Long> count(Map<String, UserStats>... visits) {

return null;



This is the main objective:

Implement Map&lt;Long, Long&gt; count(Map&lt;String, UserStats&gt;... visits) of the VisitCounter class
All branches of the company stores records of employee visitors in a map of employeeNumber mapping
to UserStats. The employeeNumber is in String form and UserStats is a User Defined Class object that
returns Optional&lt;Long&gt; for the visitCount. The management provided the above interface where all the
maps from all branches are submitted and processed every month. The method returns a map of
employeeNumber (now as Long) mapped to the their total count of visits to all branches during the



Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question