List of usage examples for java.util Map computeIfAbsent
default V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction)
From source file:Main.java
public static void main(String[] args) { Map<Integer, String> map = new HashMap<>(); for (int i = 0; i < 10; i++) { map.putIfAbsent(i, "val" + i); }//from w w w.jav a 2s. c om map.forEach((id, val) -> System.out.println(val)); map.computeIfPresent(3, (num, val) -> val + num); System.out.println(map.get(3)); // val33 map.computeIfPresent(9, (num, val) -> null); System.out.println(map.containsKey(9)); // false map.computeIfAbsent(23, num -> "val" + num); System.out.println(map.containsKey(23)); // true map.computeIfAbsent(3, num -> "bam"); System.out.println(map.get(3)); // val33 }
From source file:Main.java
/** * Adds the value to map. If the key does not exists new value set is created and the value is added to it. The * method ignores null values//from w w w .j ava2 s . com * * @param <K> * the key type * @param <V> * the value type * @param map * the map * @param key * the key * @param newValue * the new value */ public static <K, V> void addValueToSetMap(Map<K, Set<V>> map, K key, V newValue) { if (newValue == null) { return; } map.computeIfAbsent(key, k -> new LinkedHashSet<>()).add(newValue); }
From source file:Main.java
/** * Add a value to a map collection, initializing the key's collection if needed * * @param key Key whose value collection should be added to * @param valueToAdd Vale to add to the key's collection * @param map Map holding collections//from w ww . j a v a 2 s.co m */ public static <K, V> void addToCollectionMap(K key, V valueToAdd, Map<K, Collection<V>> map) { if (key != null && valueToAdd != null && map != null) { map.computeIfAbsent(key, k -> Lists.newArrayList()).add(valueToAdd); } }
From source file:Main.java
public static <T, K> Map<K, List<T>> groupBy(List<T> elements, Function<T, K> classifier) { Map<K, List<T>> result = new HashMap<>(); for (T element : elements) { K key = classifier.apply(element); result.computeIfAbsent(key, e -> new ArrayList<>()).add(element); }/* ww w . j a v a 2 s . c o m*/ return result; }
From source file:Main.java
protected static <T, K, V> void groupToMap(Map<K, List<V>> map, Collection<T> collection, Function<T, K> keyFunc, Function<T, V> valueFunc) { for (T t : collection) { K key = keyFunc.apply(t);//w w w . j a va 2s . c o m List<V> list = map.computeIfAbsent(key, k -> new ArrayList<>()); list.add(valueFunc.apply(t)); } }
From source file:io.servicecomb.foundation.common.net.URIEndpointObject.java
public static Map<String, List<String>> splitQuery(URI uri) { final Map<String, List<String>> queryPairs = new LinkedHashMap<String, List<String>>(); List<NameValuePair> pairs = URLEncodedUtils.parse(uri, StandardCharsets.UTF_8.name()); for (NameValuePair pair : pairs) { List<String> list = queryPairs.computeIfAbsent(pair.getName(), name -> { return new ArrayList<>(); });/* w ww .j ava 2 s . com*/ list.add(pair.getValue()); } return queryPairs; }
From source file:com.linecorp.armeria.server.docs.Specification.java
static Specification forServiceConfigs(Iterable<ServiceConfig> serviceConfigs, Map<Class<?>, ? extends TBase<?, ?>> sampleRequests) { final Map<Class<?>, Iterable<EndpointInfo>> map = new LinkedHashMap<>(); for (ServiceConfig c : serviceConfigs) { c.service().as(ThriftService.class).ifPresent(service -> { for (Class<?> iface : service.interfaces()) { final Class<?> serviceClass = iface.getEnclosingClass(); final List<EndpointInfo> endpoints = (List<EndpointInfo>) map.computeIfAbsent(serviceClass, cls -> new ArrayList<>()); c.pathMapping().exactPath() .ifPresent(p -> endpoints.add(EndpointInfo.of(c.virtualHost().hostnamePattern(), p, service.defaultSerializationFormat(), service.allowedSerializationFormats()))); }/*from w w w . java 2 s . c om*/ }); } return forServiceClasses(map, sampleRequests); }
From source file:com.evolveum.midpoint.schema.SelectorOptions.java
public static <T> Map<T, Collection<ItemPath>> extractOptionValues( Collection<SelectorOptions<GetOperationOptions>> options, Function<GetOperationOptions, T> supplier) { Map<T, Collection<ItemPath>> rv = new HashMap<>(); for (SelectorOptions<GetOperationOptions> selectorOption : CollectionUtils.emptyIfNull(options)) { T value = supplier.apply(selectorOption.getOptions()); if (value != null) { Collection<ItemPath> itemPaths = rv.computeIfAbsent(value, t -> new HashSet<>()); itemPaths.add(selectorOption.getItemPath()); }// w w w. jav a 2 s . co m } return rv; }
From source file:com.liferay.apio.architect.internal.body.MultipartToBodyConverter.java
/** * Reads a {@code "multipart/form"} HTTP request body into a {@link Body} * instance or fails with a {@link BadRequestException} if the input is not * a valid multipart form./*w ww .java 2 s . com*/ * * @review */ public static Body multipartToBody(HttpServletRequest request) { if (!isMultipartContent(request)) { throw new BadRequestException("Request body is not a valid multipart form"); } FileItemFactory fileItemFactory = new DiskFileItemFactory(); ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory); try { List<FileItem> fileItems = servletFileUpload.parseRequest(request); 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.github.aptd.simulation.datamodel.CXMLReader.java
/** * create the station list/*from ww w. j a v a2s . c om*/ * * @param p_network network component * @param p_agents map with agent asl scripts * @param p_factory factory * @param p_time time reference * @param p_platforms map with already generated platforms * @return unmodifyable map with stations */ private static Map<String, IStation<?>> station(final Network p_network, final Map<String, String> p_agents, final IFactory p_factory, final ITime p_time, final Map<String, IPlatform<?>> p_platforms) { final Map<String, IElement.IGenerator<IStation<?>>> l_generators = new ConcurrentHashMap<>(); final Set<IAction> l_actions = CCommon.actionsFromPackage().collect(Collectors.toSet()); final ListMultimap<String, IPlatform<?>> l_platformbystationid = Multimaps.index(p_platforms.values(), IPlatform::stationid); return Collections.<String, IStation<?>>unmodifiableMap(p_network .getInfrastructure().getOperationControlPoints().getOcp().parallelStream().filter( i -> hasagentname(i.getAny())) .map(i -> agentname(i, i.getAny())) .map(i -> l_generators .computeIfAbsent(i.getRight(), a -> stationgenerator(p_factory, p_agents.get(i.getRight()), l_actions, p_time)) .generatesingle(i.getLeft().getId(), i.getLeft().getGeoCoord().getCoord().get(0), i.getLeft().getGeoCoord().getCoord().get(1), l_platformbystationid.get(i.getLeft().getId()))) .collect(Collectors.toMap(IElement::id, i -> i))); }