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:at.gridtec.lambda4j.function.tri.TriBooleanFunction.java

/**
 * Returns a memoized (caching) version of this {@link TriBooleanFunction}. Whenever it is called, the mapping
 * between the input parameters and the return value is preserved in a cache, making subsequent calls returning the
 * memoized value instead of computing the return value again.
 * <p>/*from   w ww . j a v a  2 s.c om*/
 * Unless the function and therefore the used cache will be garbage-collected, it will keep all memoized values
 * forever.
 *
 * @return A memoized (caching) version of this {@code TriBooleanFunction}.
 * @implSpec This implementation does not allow the input parameters or return value to be {@code null} for the
 * resulting memoized function, as the cache used internally does not permit {@code null} keys or values.
 * @implNote The returned memoized function can be safely used concurrently from multiple threads which makes it
 * thread-safe.
 */
@Nonnull
default TriBooleanFunction<R> memoized() {
    if (isMemoized()) {
        return this;
    } else {
        final Map<Triple<Boolean, Boolean, Boolean>, R> cache = new ConcurrentHashMap<>();
        final Object lock = new Object();
        return (TriBooleanFunction<R> & Memoized) (value1, value2, value3) -> {
            final R returnValue;
            synchronized (lock) {
                returnValue = cache.computeIfAbsent(Triple.of(value1, value2, value3),
                        key -> apply(key.getLeft(), key.getMiddle(), key.getRight()));
            }
            return returnValue;
        };
    }
}

From source file:at.gridtec.lambda4j.function.tri.TriIntFunction.java

/**
 * Returns a memoized (caching) version of this {@link TriIntFunction}. Whenever it is called, the mapping between
 * the input parameters and the return value is preserved in a cache, making subsequent calls returning the memoized
 * value instead of computing the return value again.
 * <p>//from   ww  w.  j ava  2  s  . com
 * Unless the function and therefore the used cache will be garbage-collected, it will keep all memoized values
 * forever.
 *
 * @return A memoized (caching) version of this {@code TriIntFunction}.
 * @implSpec This implementation does not allow the input parameters or return value to be {@code null} for the
 * resulting memoized function, as the cache used internally does not permit {@code null} keys or values.
 * @implNote The returned memoized function can be safely used concurrently from multiple threads which makes it
 * thread-safe.
 */
@Nonnull
default TriIntFunction<R> memoized() {
    if (isMemoized()) {
        return this;
    } else {
        final Map<Triple<Integer, Integer, Integer>, R> cache = new ConcurrentHashMap<>();
        final Object lock = new Object();
        return (TriIntFunction<R> & Memoized) (value1, value2, value3) -> {
            final R returnValue;
            synchronized (lock) {
                returnValue = cache.computeIfAbsent(Triple.of(value1, value2, value3),
                        key -> apply(key.getLeft(), key.getMiddle(), key.getRight()));
            }
            return returnValue;
        };
    }
}

From source file:at.gridtec.lambda4j.predicate.bi.BiPredicate2.java

/**
 * Returns a memoized (caching) version of this {@link BiPredicate2}. Whenever it is called, the mapping between the
 * input parameters and the return value is preserved in a cache, making subsequent calls returning the memoized
 * value instead of computing the return value again.
 * <p>//from www.  ja  v a2s .  com
 * Unless the predicate and therefore the used cache will be garbage-collected, it will keep all memoized values
 * forever.
 *
 * @return A memoized (caching) version of this {@code BiPredicate2}.
 * @implSpec This implementation does not allow the input parameters or return value to be {@code null} for the
 * resulting memoized predicate, as the cache used internally does not permit {@code null} keys or values.
 * @implNote The returned memoized predicate can be safely used concurrently from multiple threads which makes it
 * thread-safe.
 */
@Nonnull
default BiPredicate2<T, U> memoized() {
    if (isMemoized()) {
        return this;
    } else {
        final Map<Pair<T, U>, Boolean> cache = new ConcurrentHashMap<>();
        final Object lock = new Object();
        return (BiPredicate2<T, U> & Memoized) (t, u) -> {
            final boolean returnValue;
            synchronized (lock) {
                returnValue = cache.computeIfAbsent(Pair.of(t, u), key -> test(key.getLeft(), key.getRight()));
            }
            return returnValue;
        };
    }
}

From source file:at.gridtec.lambda4j.function.tri.TriDoubleFunction.java

/**
 * Returns a memoized (caching) version of this {@link TriDoubleFunction}. Whenever it is called, the mapping
 * between the input parameters and the return value is preserved in a cache, making subsequent calls returning the
 * memoized value instead of computing the return value again.
 * <p>//from  ww w. j a va2s  .co m
 * Unless the function and therefore the used cache will be garbage-collected, it will keep all memoized values
 * forever.
 *
 * @return A memoized (caching) version of this {@code TriDoubleFunction}.
 * @implSpec This implementation does not allow the input parameters or return value to be {@code null} for the
 * resulting memoized function, as the cache used internally does not permit {@code null} keys or values.
 * @implNote The returned memoized function can be safely used concurrently from multiple threads which makes it
 * thread-safe.
 */
@Nonnull
default TriDoubleFunction<R> memoized() {
    if (isMemoized()) {
        return this;
    } else {
        final Map<Triple<Double, Double, Double>, R> cache = new ConcurrentHashMap<>();
        final Object lock = new Object();
        return (TriDoubleFunction<R> & Memoized) (value1, value2, value3) -> {
            final R returnValue;
            synchronized (lock) {
                returnValue = cache.computeIfAbsent(Triple.of(value1, value2, value3),
                        key -> apply(key.getLeft(), key.getMiddle(), key.getRight()));
            }
            return returnValue;
        };
    }
}

From source file:at.gridtec.lambda4j.function.tri.TriCharFunction.java

/**
 * Returns a memoized (caching) version of this {@link TriCharFunction}. Whenever it is called, the mapping between
 * the input parameters and the return value is preserved in a cache, making subsequent calls returning the memoized
 * value instead of computing the return value again.
 * <p>//www. java 2 s.c o m
 * Unless the function and therefore the used cache will be garbage-collected, it will keep all memoized values
 * forever.
 *
 * @return A memoized (caching) version of this {@code TriCharFunction}.
 * @implSpec This implementation does not allow the input parameters or return value to be {@code null} for the
 * resulting memoized function, as the cache used internally does not permit {@code null} keys or values.
 * @implNote The returned memoized function can be safely used concurrently from multiple threads which makes it
 * thread-safe.
 */
@Nonnull
default TriCharFunction<R> memoized() {
    if (isMemoized()) {
        return this;
    } else {
        final Map<Triple<Character, Character, Character>, R> cache = new ConcurrentHashMap<>();
        final Object lock = new Object();
        return (TriCharFunction<R> & Memoized) (value1, value2, value3) -> {
            final R returnValue;
            synchronized (lock) {
                returnValue = cache.computeIfAbsent(Triple.of(value1, value2, value3),
                        key -> apply(key.getLeft(), key.getMiddle(), key.getRight()));
            }
            return returnValue;
        };
    }
}

From source file:com.haulmont.cuba.core.sys.MetadataLoader.java

protected void assignMetaAnnotationValueFromXml(String annName, XmlAnnotation xmlAnn,
        Map<String, Object> metaAnnotations) {
    if (xmlAnn.value != null) {
        metaAnnotations.put(annName, xmlAnn.value);
        if (!xmlAnn.attributes.isEmpty()) {
            log.warn("Attributes of {} meta-annotation are ignored because a value is set", annName);
        }//  www  .j a v a2 s. c  o  m
    } else {
        Object annValue = metaAnnotations.computeIfAbsent(annName, k -> new LinkedHashMap<>());
        if (annValue instanceof Map) {
            //noinspection unchecked
            ((Map) annValue).putAll(xmlAnn.attributes);
        } else {
            log.warn("Meta-annotation {} has value {} and cannot be re-assigned by annotation attributes",
                    annName, annValue);
        }
    }
}

From source file:io.kamax.mxisd.lookup.provider.DnsLookupProvider.java

@Override
public List<ThreePidMapping> populate(List<ThreePidMapping> mappings) {
    Map<String, List<ThreePidMapping>> domains = new HashMap<>();

    for (ThreePidMapping mapping : mappings) {
        if (!ThreePidMedium.Email.is(mapping.getMedium())) {
            log.info("Skipping unsupported type {} for {}", mapping.getMedium(), mapping.getValue());
            continue;
        }/*from   ww  w  .j a  va  2  s. c  o  m*/

        Optional<String> domainOpt = getDomain(mapping.getValue());
        if (!domainOpt.isPresent()) {
            log.warn("No domain for 3PID {}", mapping.getValue());
            continue;
        }

        String domain = domainOpt.get();
        List<ThreePidMapping> domainMappings = domains.computeIfAbsent(domain, s -> new ArrayList<>());
        domainMappings.add(mapping);
    }

    log.info("Looking mappings across {} domains", domains.keySet().size());
    ForkJoinPool pool = ForkJoinPool.commonPool();
    RecursiveTask<List<ThreePidMapping>> task = new RecursiveTask<List<ThreePidMapping>>() {

        @Override
        protected List<ThreePidMapping> compute() {
            List<ThreePidMapping> mappingsFound = new ArrayList<>();
            List<DomainBulkLookupTask> tasks = new ArrayList<>();

            for (String domain : domains.keySet()) {
                DomainBulkLookupTask domainTask = new DomainBulkLookupTask(domain, domains.get(domain));
                domainTask.fork();
                tasks.add(domainTask);
            }

            for (DomainBulkLookupTask task : tasks) {
                mappingsFound.addAll(task.join());
            }

            return mappingsFound;
        }
    };
    pool.submit(task);
    pool.shutdown();

    List<ThreePidMapping> mappingsFound = task.join();
    log.info("Found {} mappings overall", mappingsFound.size());
    return mappingsFound;
}

From source file:de.metas.ui.web.process.ProcessInstance.java

private final IDocumentViewSelection createView(final ProcessInfo processInfo,
        final RecordsToOpen recordsToOpen) {
    final List<TableRecordReference> recordRefs = recordsToOpen.getRecords();
    if (recordRefs.isEmpty()) {
        return null; // shall not happen
    }//from   w ww .j  a va2s.  com

    final int adWindowId_Override = recordsToOpen.getAD_Window_ID(); // optional

    //
    // Create view create request builders from current records
    final Map<Integer, JSONCreateDocumentViewRequest.Builder> viewRequestBuilders = new HashMap<>();
    for (final TableRecordReference recordRef : recordRefs) {
        final int recordWindowId = adWindowId_Override > 0 ? adWindowId_Override
                : RecordZoomWindowFinder.findAD_Window_ID(recordRef);
        final JSONCreateDocumentViewRequest.Builder viewRequestBuilder = viewRequestBuilders.computeIfAbsent(
                recordWindowId,
                key -> JSONCreateDocumentViewRequest.builder(recordWindowId, JSONViewDataType.grid));

        viewRequestBuilder.addFilterOnlyId(recordRef.getRecord_ID());
    }
    // If there is no view create request builder there stop here (shall not happen)
    if (viewRequestBuilders.isEmpty()) {
        return null;
    }

    //
    // Create the view create request from first builder that we have.
    if (viewRequestBuilders.size() > 1) {
        logger.warn("More than one views to be created found for {}. Creating only the first view.",
                recordRefs);
    }
    final JSONCreateDocumentViewRequest viewRequest = viewRequestBuilders.values().iterator().next()
            .setReferencing(extractJSONReferencing(processInfo)).build();

    //
    // Create the view and set its ID to our process result.
    final IDocumentViewSelection view = documentViewsRepo.createView(viewRequest);
    return view;
}

From source file:com.liferay.apio.architect.impl.jaxrs.json.reader.MultipartBodyMessageBodyReader.java

@Override
public Body readFrom(Class<Body> clazz, Type genericType, Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException {

    if (!isMultipartContent(_httpServletRequest)) {
        throw new BadRequestException("Request body is not a valid multipart form");
    }//from  w w w  .  j  a  v  a  2 s  .co m

    FileItemFactory fileItemFactory = new DiskFileItemFactory();

    ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);

    try {
        List<FileItem> fileItems = servletFileUpload.parseRequest(_httpServletRequest);

        Iterator<FileItem> iterator = fileItems.iterator();

        Map<String, String> values = new HashMap<>();
        Map<String, BinaryFile> binaryFiles = new HashMap<>();
        Map<String, Map<Integer, String>> indexedValueLists = new HashMap<>();
        Map<String, Map<Integer, BinaryFile>> indexedFileLists = new HashMap<>();

        while (iterator.hasNext()) {
            FileItem fileItem = iterator.next();

            String name = fileItem.getFieldName();

            Matcher matcher = _arrayPattern.matcher(name);

            if (matcher.matches()) {
                int index = Integer.parseInt(matcher.group(2));

                String actualName = matcher.group(1);

                _storeFileItem(fileItem, value -> {
                    Map<Integer, String> indexedMap = indexedValueLists.computeIfAbsent(actualName,
                            __ -> new HashMap<>());

                    indexedMap.put(index, value);
                }, binaryFile -> {
                    Map<Integer, BinaryFile> indexedMap = indexedFileLists.computeIfAbsent(actualName,
                            __ -> new HashMap<>());

                    indexedMap.put(index, binaryFile);
                });
            } else {
                _storeFileItem(fileItem, value -> values.put(name, value),
                        binaryFile -> binaryFiles.put(name, binaryFile));
            }
        }

        Map<String, List<String>> valueLists = _flattenMap(indexedValueLists);

        Map<String, List<BinaryFile>> fileLists = _flattenMap(indexedFileLists);

        return Body.create(key -> Optional.ofNullable(values.get(key)),
                key -> Optional.ofNullable(valueLists.get(key)), key -> Optional.ofNullable(fileLists.get(key)),
                key -> Optional.ofNullable(binaryFiles.get(key)));
    } catch (FileUploadException | IndexOutOfBoundsException | NumberFormatException e) {

        throw new BadRequestException("Request body is not a valid multipart form", e);
    }
}

From source file:com.thinkbiganalytics.feedmgr.rest.model.RegisteredTemplate.java

public void initializeProcessors() {
    Map<String, Processor> processorMap = new HashMap<>();
    Map<String, Processor> inputProcessorMap = new HashMap<>();
    Map<String, Processor> nonInputProcessorMap = new HashMap<>();

    properties.stream().forEach(property -> {
        processorMap.computeIfAbsent(property.getProcessorId(),
                processorId -> new Processor(property.getProcessorId())).addProperty(property);
        if (property.isInputProperty()) {
            //dont allow the cleanup processor as a valid input selection
            if (property.isInputProperty()
                    && !NifiProcessUtil.CLEANUP_TYPE.equalsIgnoreCase(property.getProcessorType())) {
                inputProcessorMap.computeIfAbsent(property.getProcessorId(),
                        processorId -> processorMap.get(property.getProcessorId()));
            }//from w  w  w. ja v a  2  s.  com
            //mark the template as allowing preconditions if it has an input of TriggerFeed
            if (NifiProcessUtil.TRIGGER_FEED_TYPE.equalsIgnoreCase(property.getProcessorType())
                    && !this.isAllowPreconditions()) {
                this.setAllowPreconditions(true);
            }
        } else {
            nonInputProcessorMap.computeIfAbsent(property.getProcessorId(),
                    processorId -> processorMap.get(property.getProcessorId()));
        }

    });

    inputProcessors = Lists.newArrayList(inputProcessorMap.values());
    nonInputProcessors = Lists.newArrayList(nonInputProcessorMap.values());

}