We want to connect the people who have knowledge to the people who need it, to bring together people with different perspectives so they can understand each other better, and to empower everyone to share their knowledge.
import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import lombok.AllArgsConstructor; public class VisitCounterExample { public static void main(String[] args) { Map[] visits = new Map[3]; visits[0] = new HashMap(); visits[0].put("1", new UserStats(Optional.of(10L))); visits[0].put("2", new UserStats(Optional.empty())); visits[0].put("3", new UserStats(Optional.of(10L))); visits[2] = new HashMap(); visits[2].put("1", new UserStats(Optional.of(10L))); visits[2].put("2", new UserStats(Optional.empty())); visits[2].put("3", new UserStats(Optional.of(20L))); System.out.println(new VisitCounterExample().count(visits)); } Map count(Map... visits) { return Arrays.stream(visits) .filter(Objects::nonNull) .map(userStatsById -> userStatsById .entrySet() .stream() .filter(it -> isNumber(it.getKey())) .filter(it -> it.getValue().getVisitCount().isPresent()) .collect( Collectors.toMap( it -> Long.parseLong(it.getKey()), it -> it.getValue().getVisitCount().get() ) ) ) .flatMap(it -> it.entrySet().stream()) .collect( Collectors.toMap( Map.Entry::getKey, Map.Entry::getValue, Long::sum ) ); } private static boolean isNumber(String str) { try { Long.parseLong(str); return true; } catch (NumberFormatException e) { return false; } } @AllArgsConstructor public static class UserStats { private Optional visitCount; public Optional getVisitCount() { return visitCount; } } }
2.2K Point(s)
1.2K Point(s)
313 Point(s)
178 Point(s)
138 Point(s)
Input your email to receive reset password link, or if you remember your password, you can click