Example usage for java.util Map computeIfAbsent

List of usage examples for java.util Map computeIfAbsent

Introduction

In this page you can find the example usage for java.util Map computeIfAbsent.

Prototype

default V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) 

Source Link

Document

If the specified key is not already associated with a value (or is mapped to null ), attempts to compute its value using the given mapping function and enters it into this map unless null .

Usage

From source file:org.shredzone.cilla.admin.spring.ViewScope.java

@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
    Map<String, Object> viewMap = FacesContext.getCurrentInstance().getViewRoot().getViewMap();
    return viewMap.computeIfAbsent(name, it -> objectFactory.getObject());
}

From source file:com.github.aptd.simulation.datamodel.CXMLReader.java

/**
 * create the platforms of all stations/*from  w ww  .ja  v a 2 s . c o m*/
 *
 * @param p_network network component
 * @param p_agents map with agent asl scripts
 * @param p_factory factory
 * @param p_time time reference
 * @return unmodifyable map with platforms
 */
private static Map<String, IPlatform<?>> platform(final Network p_network, final Map<String, String> p_agents,
        final IFactory p_factory, final ITime p_time) {
    final Map<String, IElement.IGenerator<IPlatform<?>>> l_generators = new ConcurrentHashMap<>();
    final Set<IAction> l_actions = CCommon.actionsFromPackage().collect(Collectors.toSet());
    return Collections.<String, IPlatform<?>>unmodifiableMap(p_network.getInfrastructure()
            .getOperationControlPoints().getOcp().parallelStream()
            .flatMap(ocp -> ocp.getAny().stream().filter(a -> a instanceof StationLayout).findAny()
                    .map(a -> ((StationLayout) a).getPlatform().stream()
                            .map(p -> new ImmutablePair<EOcp, PlatformType>(ocp, p)))
                    .orElse(Stream.of()))
            .filter(i -> i.getRight().getAgentRef() != null)
            .map(i -> l_generators
                    .computeIfAbsent(i.getRight().getAgentRef().getAgent(),
                            a -> platformgenerator(p_factory,
                                    p_agents.get(i.getRight().getAgentRef().getAgent()), l_actions, p_time))
                    .generatesingle(i.getLeft().getId() + "-track-" + i.getRight().getNumber(),
                            i.getLeft().getId()))
            .collect(Collectors.toMap(IElement::id, i -> i)));
}

From source file:cn.edu.zjnu.acm.judge.contest.ContestController.java

@ResponseBody
@GetMapping(value = "standing", produces = APPLICATION_JSON_VALUE)
public UserStanding[] standing(@PathVariable("contestId") long contestId) {
    Map<String, UserStanding> hashMap = new HashMap<>(80);
    contestMapper.standing(contestId)//w ww  .  j a v a  2 s .c o m
            .forEach(standing -> hashMap.computeIfAbsent(standing.getUser(), UserStanding::new)
                    .add(standing.getProblem(), standing.getTime(), standing.getPenalty()));
    contestMapper.attenders(contestId).forEach(attender -> Optional.ofNullable(hashMap.get(attender.getId()))
            .ifPresent(us -> us.setNick(attender.getNick())));
    UserStanding[] standings = hashMap.values().stream().sorted(UserStanding.COMPARATOR)
            .toArray(UserStanding[]::new);
    setIndexes(standings, Comparator.nullsFirst(UserStanding.COMPARATOR), UserStanding::setIndex);
    return standings;
}

From source file:com.netflix.spinnaker.fiat.permissions.DefaultPermissionsResolver.java

private Map<String, Collection<Role>> getAndMergeUserRoles(@NonNull Collection<ExternalUser> users) {
    List<String> usernames = users.stream().map(ExternalUser::getId).collect(Collectors.toList());

    Map<String, Collection<Role>> userToRoles = userRolesProvider.multiLoadRoles(usernames);

    users.forEach(user -> {/*from  w  w  w . j a v a2  s  . c  o m*/
        userToRoles.computeIfAbsent(user.getId(), ignored -> new ArrayList<>()).addAll(user.getExternalRoles());
    });

    if (log.isDebugEnabled()) {
        try {
            log.debug("Multi-loaded roles: \n"
                    + mapper.writerWithDefaultPrettyPrinter().writeValueAsString(userToRoles));
        } catch (Exception e) {
            log.debug("Exception writing roles", e);
        }
    }
    return userToRoles;
}

From source file:com.thinkbiganalytics.nifi.provenance.repo.ConfigurationProperties.java

public void populateChanges(Map<String, PropertyChange> changes, boolean old) {
    changes.computeIfAbsent(BACKUP_LOCATION_KEY, key -> new PropertyChange(key)).setValue(backupLocation, old);
    changes.computeIfAbsent(MAX_FEED_EVENTS_KEY, key -> new PropertyChange(key)).setValue(maxFeedEvents + "",
            old);// ww w  .  j a  va2  s  . c  om
    changes.computeIfAbsent(RUN_INTERVAL_KEY, key -> new PropertyChange(key)).setValue(runInterval + "", old);
    changes.computeIfAbsent(ORPHAN_CHILD_FLOW_FILE_PROCESSORS_KEY, key -> new PropertyChange(key))
            .setValue(orphanChildFlowFileProcessorsString, old);
}

From source file:org.apache.servicecomb.foundation.vertx.http.StandardHttpServletRequestEx.java

private void mergeParameterMaptoListMap(Map<String, List<String>> listMap) {
    for (Entry<String, String[]> entry : super.getParameterMap().entrySet()) {
        List<String> values = listMap.computeIfAbsent(entry.getKey(), k -> new ArrayList<>());
        // follow servlet behavior, inherited value first, and then body value
        values.addAll(0, Arrays.asList(entry.getValue()));
    }/*from   ww  w .ja v a 2 s  .c o  m*/
}

From source file:com.redhat.ipaas.api.v1.rest.DataManager.java

public <T extends WithId> T fetch(String kind, String id) {
    Map<String, WithId> cache = caches.getCache(kind);
    return (T) cache.computeIfAbsent(id, i -> doWithDataAccessObject(kind, d -> (T) d.fetch(i)));
}

From source file:com.yahoo.bard.webservice.web.TableFullViewProcessor.java

/**
 * Method to provide full view of the tables which includes grains, metrics and dimensions.
 *
 * @param logicalTables  Set of logical tables
 * @param uriInfo  Uri information to construct the uri's
 *
 * @return List of table details with all the associated meta info
 *//*from   w ww.j av  a 2  s .  c  o  m*/
@Override
public List<TableView> formatTables(Set<LogicalTable> logicalTables, UriInfo uriInfo) {

    //Map to keep meta info of the logical table
    Map<String, TableView> tablesMeta = new HashMap<>();
    //Map to keep list of time grain details for the logical table
    Map<String, List<TableGrainView>> grainsData = new HashMap<>();

    for (LogicalTable logicalTable : logicalTables) {
        //An array list to store grain level definition of given logical table
        List<TableGrainView> grains = grainsData.computeIfAbsent(logicalTable.getName(),
                (ignore) -> new ArrayList<>());

        grains.add(formatTableGrain(logicalTable, logicalTable.getGranularity().getName(), uriInfo));

        if (tablesMeta.get(logicalTable.getName()) == null) {
            tablesMeta.put(logicalTable.getName(), formatTable(logicalTable, uriInfo));
        }
    }

    List<TableView> tableViewList = new ArrayList<>();

    Set<Map.Entry<String, TableView>> entrySet = tablesMeta.entrySet();
    for (Map.Entry<String, TableView> entry : entrySet) {
        TableView tableView = entry.getValue();
        tableView.put("timeGrains", grainsData.get(entry.getKey()));
        tableViewList.add(tableView);
    }
    return tableViewList;
}

From source file:com.oneops.transistor.util.CloudUtil.java

private Map<String, TreeSet<String>> getMissingCloudServices(String cloud, Set<String> cloudServices,
        Set<String> requiredServices) {
    Map<String, TreeSet<String>> missingCloud2Services = new TreeMap<>();
    requiredServices.stream().filter(s -> !cloudServices.contains(s))
            .forEach(s -> missingCloud2Services.computeIfAbsent(cloud, k -> new TreeSet<>()).add(s));
    logger.debug("cloud: " + cloud + " required services:: " + requiredServices.toString() + " missingServices "
            + missingCloud2Services.keySet());

    return missingCloud2Services;
}

From source file:com.github.aptd.simulation.datamodel.CXMLReader.java

/**
 * create the train list/*from   w  w  w  .  java 2s. c  om*/
 *
 * @param p_network network component
 * @param p_agents map with agent asl scripts
 * @param p_factory factory
 * @return unmodifiable map with trains
 */
private static Pair<Map<String, ITrain<?>>, Map<String, IDoor<?>>> train(final Network p_network,
        final Map<String, String> p_agents, final IFactory p_factory, final ITime p_time,
        final double p_minfreetimetoclose) {
    final String l_dooragent = IStatefulElement.getDefaultAsl("door");
    final Map<String, IElement.IGenerator<ITrain<?>>> l_generators = new ConcurrentHashMap<>();
    final Set<IAction> l_actions = CCommon.actionsFromPackage().collect(Collectors.toSet());
    final IElement.IGenerator<IDoor<?>> l_doorgenerator = doorgenerator(p_factory, l_dooragent, l_actions,
            p_time);
    final Map<String, AtomicLong> l_doorcount = Collections.synchronizedMap(new HashMap<>());
    final Map<String, IDoor<?>> l_doors = Collections.synchronizedMap(new HashMap<>());
    return new ImmutablePair<>(
            Collections.<String, ITrain<?>>unmodifiableMap(
                    p_network.getTimetable().getTrains().getTrain().parallelStream()
                            .filter(i -> hasagentname(i.getAny3())).map(i -> agentname(i, i.getAny3()))
                            .map(i -> l_generators
                                    .computeIfAbsent(i.getRight(),
                                            a -> traingenerator(p_factory, p_agents.get(i.getRight()),
                                                    l_actions, p_time))
                                    .generatesingle(i.getLeft().getId(),
                                            i.getLeft().getTrainPartSequence().stream().flatMap(ref -> {
                                                // @todo support multiple train parts
                                                final EOcpTT[] l_tts = ((ETrainPart) ref.getTrainPartRef()
                                                        .get(0).getRef()).getOcpsTT().getOcpTT()
                                                                .toArray(new EOcpTT[0]);
                                                final CTrain.CTimetableEntry[] l_entries = new CTrain.CTimetableEntry[l_tts.length];
                                                for (int j = 0; j < l_tts.length; j++) {
                                                    final EArrivalDepartureTimes l_times = l_tts[j].getTimes()
                                                            .stream()
                                                            .filter(t -> t.getScope()
                                                                    .equalsIgnoreCase("published"))
                                                            .findAny().orElseThrow(() -> new CSemanticException(
                                                                    "missing published times"));
                                                    l_entries[j] = new CTrain.CTimetableEntry(
                                                            j < 1 ? 0.0
                                                                    : ((ETrack) l_tts[j - 1].getSectionTT()
                                                                            .getTrackRef().get(0).getRef())
                                                                                    .getTrackTopology()
                                                                                    .getTrackEnd().getPos()
                                                                                    .doubleValue(),
                                                            ((EOcp) l_tts[j].getOcpRef()).getId(),
                                                            l_tts[j].getStopDescription().getOtherAttributes()
                                                                    .getOrDefault(PLATFORM_REF_ATTRIBUTE, null),
                                                            l_times.getArrival() == null ? null
                                                                    : l_times.getArrival().toGregorianCalendar()
                                                                            .toZonedDateTime()
                                                                            .with(LocalDate.from(p_time
                                                                                    .current()
                                                                                    .atZone(ZoneId
                                                                                            .systemDefault())))
                                                                            .toInstant(),
                                                            l_times.getDeparture() == null ? null
                                                                    : l_times.getDeparture()
                                                                            .toGregorianCalendar()
                                                                            .toZonedDateTime()
                                                                            .with(LocalDate.from(p_time
                                                                                    .current()
                                                                                    .atZone(ZoneId
                                                                                            .systemDefault())))
                                                                            .toInstant());
                                                }
                                                return Arrays.stream(l_entries);
                                            }), i.getLeft().getTrainPartSequence().stream()
                                                    // @todo support multiple train parts
                                                    .map(s -> (ETrainPart) s.getTrainPartRef().get(0).getRef())
                                                    .map(p -> (EFormation) p.getFormationTT().getFormationRef())
                                                    .flatMap(f -> f.getTrainOrder().getVehicleRef().stream())
                                                    .map(r -> new ImmutablePair<BigInteger, TDoors>(
                                                            r.getVehicleCount(),
                                                            ((EVehicle) r.getVehicleRef()).getWagon()
                                                                    .getPassenger().getDoors()))
                                                    .flatMap(v -> IntStream
                                                            .range(0,
                                                                    v.getLeft().intValue() * v.getRight()
                                                                            .getNumber().intValue())
                                                            .mapToObj(j -> l_doors.computeIfAbsent("door-"
                                                                    + i.getLeft().getId() + "-"
                                                                    + l_doorcount
                                                                            .computeIfAbsent(i.getLeft()
                                                                                    .getId(),
                                                                                    id -> new AtomicLong(1L))
                                                                            .getAndIncrement(),
                                                                    id -> l_doorgenerator.generatesingle(id,
                                                                            i.getLeft().getId(),
                                                                            v.getRight().getEntranceWidth()
                                                                                    .doubleValue()
                                                                                    / v.getRight().getNumber()
                                                                                            .longValue(),
                                                                            p_minfreetimetoclose))))
                                                    .collect(Collectors.toList())))
                            .collect(Collectors.toMap(IElement::id, i -> i))),
            l_doors);
}