Java Code Examples for java.util.Map#computeIfAbsent()

The following examples show how to use java.util.Map#computeIfAbsent() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ComponentCountTask.java    From nifi with Apache License 2.0 6 votes vote down vote up
private void countProcessors(final Collection<ProcessorNode> processors, final List<String> details) {
    final Map<String, Map<ScheduledState, Integer>> typeMap = new HashMap<>();

    for (final ProcessorNode procNode : processors) {
        final String componentType = procNode.getComponentType();

        final ScheduledState scheduledState = procNode.getScheduledState();
        final Map<ScheduledState, Integer> stateCounts = typeMap.computeIfAbsent(componentType, key -> new HashMap<>());
        final Integer count = stateCounts.computeIfAbsent(scheduledState, key -> 0);
        stateCounts.put(scheduledState, count + 1);
    }

    for (final Map.Entry<String, Map<ScheduledState, Integer>> typeEntry : typeMap.entrySet()) {
        final String type = typeEntry.getKey();
        final Map<ScheduledState, Integer> stateMap = typeEntry.getValue();

        final int total = stateMap.values().stream().mapToInt(Integer::intValue).sum();
        details.add(type + " : " + total + " Total, " + stateMap.toString().toLowerCase());
    }

    if (typeMap.isEmpty()) {
        details.add("No Processors");
    }
}
 
Example 2
Source File: MetadataVerificationTests.java    From start.spring.io with Apache License 2.0 6 votes vote down vote up
private List<RemoteRepository> getRepositories(Dependency dependency, Version bootVersion,
		List<BillOfMaterials> boms) {
	Map<String, RemoteRepository> repositories = new HashMap<>();
	repositories.put("central", DependencyResolver.mavenCentral);
	String dependencyRepository = dependency.getRepository();
	if (dependencyRepository != null) {
		repositories.computeIfAbsent(dependencyRepository, this::repositoryForId);
	}
	for (BillOfMaterials bom : boms) {
		for (String repository : bom.getRepositories()) {
			repositories.computeIfAbsent(repository, this::repositoryForId);
		}
	}
	if (!bootVersion.getQualifier().getId().equals("RELEASE")) {
		repositories.computeIfAbsent("spring-milestones", this::repositoryForId);
		if (bootVersion.getQualifier().getId().contains("SNAPSHOT")) {
			repositories.computeIfAbsent("spring-snapshots", this::repositoryForId);
		}
	}
	return new ArrayList<>(repositories.values());
}
 
Example 3
Source File: DisjointSet.java    From presto with Apache License 2.0 5 votes vote down vote up
public Collection<Set<T>> getEquivalentClasses()
{
    // map from root element to all element in the tree
    Map<T, Set<T>> rootToTreeElements = new LinkedHashMap<>();
    for (Map.Entry<T, Entry<T>> entry : map.entrySet()) {
        T node = entry.getKey();
        T root = findInternal(node);
        rootToTreeElements.computeIfAbsent(root, unused -> new LinkedHashSet<>());
        rootToTreeElements.get(root).add(node);
    }
    return rootToTreeElements.values();
}
 
Example 4
Source File: OfferAccepter.java    From dcos-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Groups recommendations by agent, while preserving their existing order.
 */
@VisibleForTesting
protected static Map<String, List<OfferRecommendation>> groupByAgent(
    List<OfferRecommendation> recommendations)
{
  // Use TreeMap for consistent ordering. Not required but simplifies testing, and nice to have consistent output.
  final Map<String, List<OfferRecommendation>> recommendationsByAgent = new TreeMap<>();
  for (OfferRecommendation recommendation : recommendations) {
    final String agentId = recommendation.getAgentId().getValue();
    List<OfferRecommendation> agentRecommendations =
        recommendationsByAgent.computeIfAbsent(agentId, k -> new ArrayList<>());
    agentRecommendations.add(recommendation);
  }
  return recommendationsByAgent;
}
 
Example 5
Source File: FlinkCheckpointDuration.java    From garmadon with Apache License 2.0 5 votes vote down vote up
@Override
public void process(Long timestamp, String applicationId, FlinkEventProtos.JobEvent event) {
    Map<String, DurationCounter> countersByJobKey = countersByAppId.computeIfAbsent(applicationId, s -> new HashMap<>());

    long duration = event.getLastCheckpointDuration();

    String jobKey = event.getJobName();
    DurationCounter counter = countersByJobKey.computeIfAbsent(jobKey, s -> new DurationCounter(jobKey, duration));
    counter.setDuration(duration);
}
 
Example 6
Source File: IslandInfo.java    From uSkyBlock with GNU General Public License v3.0 5 votes vote down vote up
@Override
@NotNull
public Map<Material, Integer> getBlockLimits() {
    Map<Material, Integer> blockLimitMap = new HashMap<>();
    ConfigurationSection membersSection = config.getConfigurationSection("party.members");
    if (membersSection != null) {
        for (String memberName : membersSection.getKeys(false)) {
            ConfigurationSection memberSection = membersSection.getConfigurationSection(memberName);
            if (memberSection != null) {
                if (memberSection.isConfigurationSection("blockLimits")) {
                    ConfigurationSection blockLimits = memberSection.getConfigurationSection("blockLimits");
                    for (String material : blockLimits.getKeys(false)) {
                        Material type = Material.matchMaterial(material);
                        if (type != null) {
                            blockLimitMap.computeIfAbsent(type, (k) -> {
                                int memberMax = blockLimits.getInt(material, 0);
                                return blockLimitMap.compute(type, (key, oldValue) ->
                                        oldValue != null && memberMax > 0 ? Math.max(memberMax, oldValue) : null);
                            });
                        }
                    }
                }
            }
        }
    }
    return blockLimitMap;
}
 
Example 7
Source File: SideInputContainer.java    From beam with Apache License 2.0 5 votes vote down vote up
/** Index the provided values by all {@link BoundedWindow windows} in which they appear. */
private Map<BoundedWindow, Collection<WindowedValue<?>>> indexValuesByWindow(
    Iterable<? extends WindowedValue<?>> values) {
  Map<BoundedWindow, Collection<WindowedValue<?>>> valuesPerWindow = new HashMap<>();
  for (WindowedValue<?> value : values) {
    for (BoundedWindow window : value.getWindows()) {
      Collection<WindowedValue<?>> windowValues =
          valuesPerWindow.computeIfAbsent(window, k -> new ArrayList<>());
      windowValues.add(value);
    }
  }
  return valuesPerWindow;
}
 
Example 8
Source File: ExportGeometryAction.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
private static Map<Class<?>, List<SimpleFeature>> createGeometryToFeaturesListMap(VectorDataNode vectorNode) throws TransformException,
                                                                                                                    SchemaException {
    FeatureCollection<SimpleFeatureType, SimpleFeature> featureCollection = vectorNode.getFeatureCollection();
    CoordinateReferenceSystem crs = vectorNode.getFeatureType().getCoordinateReferenceSystem();
    if (crs == null) {   // for pins and GCPs crs is null
        crs = vectorNode.getProduct().getSceneCRS();
    }
    final CoordinateReferenceSystem modelCrs;
    if (vectorNode.getProduct().getSceneGeoCoding() instanceof CrsGeoCoding) {
        modelCrs = vectorNode.getProduct().getSceneCRS();
    } else {
        modelCrs = DefaultGeographicCRS.WGS84;
    }

    // Not using ReprojectingFeatureCollection - it is reprojecting all geometries of a feature
    // but we want to reproject the default geometry only
    GeometryCoordinateSequenceTransformer transformer = createTransformer(crs, modelCrs);

    Map<Class<?>, List<SimpleFeature>> featureListMap = new HashMap<>();
    final FeatureIterator<SimpleFeature> featureIterator = featureCollection.features();
    // The schema needs to be reprojected. We need to build a new feature be cause we can't change the schema.
    // It is necessary to have this reprojected schema, because otherwise the shapefile is not correctly georeferenced.
    SimpleFeatureType schema = featureCollection.getSchema();
    SimpleFeatureType transformedSchema = FeatureTypes.transform(schema, modelCrs);
    while (featureIterator.hasNext()) {
        SimpleFeature feature = featureIterator.next();
        Object defaultGeometry = feature.getDefaultGeometry();
        feature.setDefaultGeometry(transformer.transform((Geometry) defaultGeometry));

        Class<?> geometryType = defaultGeometry.getClass();
        List<SimpleFeature> featureList = featureListMap.computeIfAbsent(geometryType, k -> new ArrayList<>());
        SimpleFeature exportFeature = SimpleFeatureBuilder.build(transformedSchema, feature.getAttributes(), feature.getID());
        featureList.add(exportFeature);
    }
    return featureListMap;
}
 
Example 9
Source File: BattleDelegate.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Return map of adjacent territories along attack routes in battles where fighting will occur.
 */
private Map<Territory, Collection<IBattle>> getPossibleBombardingTerritories() {
  final Map<Territory, Collection<IBattle>> possibleBombardingTerritories = new HashMap<>();
  for (final Territory t : battleTracker.getPendingBattleSites(false)) {
    final IBattle battle = battleTracker.getPendingBattle(t, false, BattleType.NORMAL);
    // we only care about battles where we must fight
    // this check is really to avoid implementing getAttackingFrom() in other battle subclasses
    if (!(battle instanceof MustFightBattle)) {
      continue;
    }
    // bombarding can only occur in territories from which at least 1 land unit attacked
    final Map<Territory, Collection<Unit>> attackingFromMap =
        ((MustFightBattle) battle).getAttackingFromMap();
    for (final Territory neighbor : ((MustFightBattle) battle).getAttackingFrom()) {
      // we do not allow bombarding from certain sea zones (like if there was a kamikaze suicide
      // attack there, etc)
      if (battleTracker.noBombardAllowedFromHere(neighbor)) {
        continue;
      }
      final Collection<Unit> neighbourUnits = attackingFromMap.get(neighbor);
      // If all units from a territory are air- no bombard
      if (!neighbourUnits.isEmpty() && neighbourUnits.stream().allMatch(Matches.unitIsAir())) {
        continue;
      }
      final Collection<IBattle> battles =
          possibleBombardingTerritories.computeIfAbsent(neighbor, k -> new ArrayList<>());
      battles.add(battle);
    }
  }
  return possibleBombardingTerritories;
}
 
Example 10
Source File: MultiCurrencyAmountArray.java    From Strata with Apache License 2.0 5 votes vote down vote up
/**
 * Obtains an instance using a function to create the entries.
 * <p>
 * The function is passed the index and returns the {@code MultiCurrencyAmount} for that index.
 * 
 * @param size  the number of elements, at least size one
 * @param valueFunction  the function used to obtain each value
 * @return an instance initialized using the function
 * @throws IllegalArgumentException is size is zero or less
 */
public static MultiCurrencyAmountArray of(int size, IntFunction<MultiCurrencyAmount> valueFunction) {
  Map<Currency, double[]> map = new HashMap<>();
  for (int i = 0; i < size; i++) {
    MultiCurrencyAmount mca = valueFunction.apply(i);
    for (CurrencyAmount ca : mca.getAmounts()) {
      double[] array = map.computeIfAbsent(ca.getCurrency(), c -> new double[size]);
      array[i] = ca.getAmount();
    }
  }
  return new MultiCurrencyAmountArray(size, MapStream.of(map).mapValues(array -> DoubleArray.ofUnsafe(array)).toMap());
}
 
Example 11
Source File: DashboardService.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Finds all dashboard with column and order set.
 * 
 * @param user
 *            the current user
 * @return a map where key is the column id, and value is the column's dashboard list.
 */
public Map<String, List<IDashboardComponent>> getAllSetDashboards( AdminUser user )
{
    Map<String, List<IDashboardComponent>> mapDashboardComponents = new HashMap<>( );

    List<IDashboardComponent> listDashboards = DashboardHome.findAll( );

    for ( IDashboardComponent dashboard : listDashboards )
    {
        int nColumn = dashboard.getZone( );
        boolean bRight = user.checkRight( dashboard.getRight( ) ) || dashboard.getRight( ).equalsIgnoreCase( ALL );

        if ( !bRight )
        {
            continue;
        }

        String strColumn = Integer.toString( nColumn );

        // find this column list
        List<IDashboardComponent> listDashboardsColumn = mapDashboardComponents.computeIfAbsent( strColumn, s -> new ArrayList<>( ) );

        // add dashboard to the list
        listDashboardsColumn.add( dashboard );
    }

    return mapDashboardComponents;
}
 
Example 12
Source File: PartitionStateHolder.java    From siddhi with Apache License 2.0 5 votes vote down vote up
@Override
public State getState() {
    String partitionFlowId = SiddhiAppContext.getPartitionFlowId();
    String groupByFlowId = SiddhiAppContext.getGroupByFlowId();
    Map<String, State> partitionStates = states.computeIfAbsent(partitionFlowId, k -> new HashMap<>());
    return partitionStates.computeIfAbsent(groupByFlowId, s -> stateFactory.createNewState());
}
 
Example 13
Source File: MaterialCockpitRowFactory.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 5 votes vote down vote up
private void addStockRowsToResult(
		@NonNull final CreateRowsRequest request,
		@NonNull final DimensionSpec dimensionSpec,
		@NonNull final Map<MainRowBucketId, MainRowWithSubRows> result)
{
	for (final I_MD_Stock stockRecord : request.getStockRecords())
	{
		final MainRowBucketId mainRowBucketId = MainRowBucketId.createInstanceForStockRecord(stockRecord, request.getDate());

		final MainRowWithSubRows mainRowBucket = result.computeIfAbsent(mainRowBucketId, key -> MainRowWithSubRows.create(key));
		mainRowBucket.addStockRecord(stockRecord, dimensionSpec, request.isIncludePerPlantDetailRows());
	}
}
 
Example 14
Source File: SupplyView.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
private static <T, R> Function<T, R> memoize(Function<T, R> fn) {
    Map<T, R> map = new ConcurrentHashMap<>();
    return x -> map.computeIfAbsent(x, fn);
}
 
Example 15
Source File: RoundRobinOperatorStateRepartitioner.java    From flink with Apache License 2.0 4 votes vote down vote up
/**
 * Group by the different named states.
 */
@SuppressWarnings("unchecked, rawtype")
private GroupByStateNameResults groupByStateMode(List<List<OperatorStateHandle>> previousParallelSubtaskStates) {

	//Reorganize: group by (State Name -> StreamStateHandle + StateMetaInfo)
	EnumMap<OperatorStateHandle.Mode,
			Map<String, List<Tuple2<StreamStateHandle, OperatorStateHandle.StateMetaInfo>>>> nameToStateByMode =
			new EnumMap<>(OperatorStateHandle.Mode.class);

	for (OperatorStateHandle.Mode mode : OperatorStateHandle.Mode.values()) {

		nameToStateByMode.put(
				mode,
				new HashMap<>());
	}

	for (List<OperatorStateHandle> previousParallelSubtaskState : previousParallelSubtaskStates) {
		for (OperatorStateHandle operatorStateHandle : previousParallelSubtaskState) {

			if (operatorStateHandle == null) {
				continue;
			}

			final Set<Map.Entry<String, OperatorStateHandle.StateMetaInfo>> partitionOffsetEntries =
				operatorStateHandle.getStateNameToPartitionOffsets().entrySet();

			for (Map.Entry<String, OperatorStateHandle.StateMetaInfo> e : partitionOffsetEntries) {
				OperatorStateHandle.StateMetaInfo metaInfo = e.getValue();

				Map<String, List<Tuple2<StreamStateHandle, OperatorStateHandle.StateMetaInfo>>> nameToState =
					nameToStateByMode.get(metaInfo.getDistributionMode());

				List<Tuple2<StreamStateHandle, OperatorStateHandle.StateMetaInfo>> stateLocations =
					nameToState.computeIfAbsent(
						e.getKey(),
						k -> new ArrayList<>(previousParallelSubtaskStates.size() * partitionOffsetEntries.size()));

				stateLocations.add(Tuple2.of(operatorStateHandle.getDelegateStateHandle(), e.getValue()));
			}
		}
	}

	return new GroupByStateNameResults(nameToStateByMode);
}
 
Example 16
Source File: OutputLineEnricher.java    From ambari-logsearch with Apache License 2.0 4 votes vote down vote up
public Map<String, Object> enrichFields(final Map<String, Object> jsonObj, final InputMarker inputMarker, final MetricData messageTruncateMetric) {
  Input input = inputMarker.getInput();
  // Update the block with the context fields
  for (Map.Entry<String, String> entry : input.getInputDescriptor().getAddFields().entrySet()) {
    if (jsonObj.get(entry.getKey()) == null || "cluster".equals(entry.getKey()) && "null".equals(jsonObj.get(entry.getKey()))) {
      jsonObj.put(entry.getKey(), entry.getValue());
    }
  }
  // TODO: Ideally most of the overrides should be configurable
  LogFeederUtil.fillMapWithFieldDefaults(jsonObj, inputMarker, true);
  if (input.isUseEventMD5() || input.isGenEventMD5()) {
    String prefix = "";
    Object logtimeObj = jsonObj.get("logtime");
    if (logtimeObj != null) {
      if (logtimeObj instanceof Date) {
        prefix = "" + ((Date) logtimeObj).getTime();
      } else {
        prefix = logtimeObj.toString();
      }
    }
    byte[] bytes = LogFeederUtil.getGson().toJson(jsonObj).getBytes();
    long eventMD5 = Hashing.md5().hashBytes(bytes).asLong();
    if (input.isGenEventMD5()) {
      jsonObj.put("event_md5", prefix + Long.toString(eventMD5));
    }
    if (input.isUseEventMD5()) {
      jsonObj.put("id", prefix + Long.toString(eventMD5));
    }
  }
  jsonObj.computeIfAbsent("event_count", k -> 1);
  if (StringUtils.isNotBlank(input.getInputDescriptor().getGroup())) {
    jsonObj.put("group", input.getInputDescriptor().getGroup());
  }
  if (inputMarker.getAllProperties().containsKey("line_number") &&
    (Integer) inputMarker.getAllProperties().get("line_number") > 0) {
    jsonObj.put("logfile_line_number", inputMarker.getAllProperties().get("line_number"));
  }
  if (!jsonObj.containsKey("level")) {
    jsonObj.put("level", LogFeederConstants.LOG_LEVEL_UNKNOWN);
  }
  if (jsonObj.containsKey("log_message")) {
    // TODO: Let's check size only for log_message for now
    String logMessage = (String) jsonObj.get("log_message");
    logMessage = truncateLongLogMessage(messageTruncateMetric, jsonObj, input, logMessage);
    jsonObj.put("message_md5", "" + Hashing.md5().hashBytes(logMessage.getBytes()).asLong());
  }

  return jsonObj;
}
 
Example 17
Source File: BratRenderer.java    From webanno with Apache License 2.0 4 votes vote down vote up
/**
 * Generates brat type definitions from the WebAnno layer definitions.
 *
 * @param aProject
 *            the project to which the layers belong
 * @param aAnnotationLayers
 *            the layers
 * @param aAnnotationService
 *            the annotation service
 * @return the brat type definitions
 */
public static Set<EntityType> buildEntityTypes(Project aProject, 
        List<AnnotationLayer> aAnnotationLayers, AnnotationSchemaService aAnnotationService)
{
    // Sort layers
    List<AnnotationLayer> layers = new ArrayList<>(aAnnotationLayers);
    layers.sort(Comparator.comparing(AnnotationLayer::getName));

    // Look up all the features once to avoid hammering the database in the loop below
    Map<AnnotationLayer, List<AnnotationFeature>> layerToFeatures = aAnnotationService
            .listSupportedFeatures(aProject).stream()
            .collect(groupingBy(AnnotationFeature::getLayer));
    
    // Now build the actual configuration
    Set<EntityType> entityTypes = new LinkedHashSet<>();
    for (AnnotationLayer layer : layers) {
        EntityType entityType = configureEntityType(layer);

        List<RelationType> arcs = new ArrayList<>();
        
        // For link features, we also need to configure the arcs, even though there is no arc
        // layer here.
        boolean hasLinkFeatures = false;
        for (AnnotationFeature f : layerToFeatures.computeIfAbsent(layer, k -> emptyList())) {
            if (!LinkMode.NONE.equals(f.getLinkMode())) {
                hasLinkFeatures = true;
                break;
            }
        }
        
        if (hasLinkFeatures) {
            String bratTypeName = TypeUtil.getUiTypeName(layer);
            arcs.add(new RelationType(layer.getName(), layer.getUiName(), bratTypeName,
                    bratTypeName, null, "triangle,5", "3,3"));
        }

        // Styles for the remaining relation and chain layers
        for (AnnotationLayer attachingLayer : getAttachingLayers(layer, layers,
                aAnnotationService)) {
            arcs.add(configureRelationType(layer, attachingLayer));
        }

        entityType.setArcs(arcs);
        entityTypes.add(entityType);
    }

    return entityTypes;
}
 
Example 18
Source File: MapUtils.java    From fdb-record-layer with Apache License 2.0 3 votes vote down vote up
/**
 * In older versions of java {@code ConcurrentHashMap.computeIfAbsent()} has an issue where threads can contend
 * on reads even when the value is present.  This method provides the same behavior as {@code computeIfAbsent}
 * but avoids such contention.
 *
 * @param map the map to use for the operation
 * @param key the key to look up
 * @param supplier a supplier to be used to generate a new value if one is not already present
 * @param <K> the key type
 * @param <V> the value type
 * @return the existing value from the map or the newly added value if no value was previously present
 */
public static <K, V> V computeIfAbsent(Map<K, V> map, K key, Function<K, V> supplier) {
    V value = map.get(key);
    if (value == null) {
        value = map.computeIfAbsent(key, supplier);
    }
    return value;
}
 
Example 19
Source File: Maps1.java    From java8-tutorial with MIT License 3 votes vote down vote up
public static void main(String[] args) {
    Map<Integer, String> map = new HashMap<>();

    for (int i = 0; i < 10; i++) {
        map.putIfAbsent(i, "val" + i);
    }

    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

    System.out.println(map.getOrDefault(42, "not found"));      // not found

    map.remove(3, "val3");
    System.out.println(map.get(3));             // val33

    map.remove(3, "val33");
    System.out.println(map.get(3));             // null

    map.merge(9, "val9", (value, newValue) -> value.concat(newValue));
    System.out.println(map.get(9));             // val9

    map.merge(9, "concat", (value, newValue) -> value.concat(newValue));
    System.out.println(map.get(9));             // val9concat
}
 
Example 20
Source File: DefaultEntityProxyFactory.java    From JALSE with Apache License 2.0 2 votes vote down vote up
/**
 * Either retrieves a proxy from the cache or creates (and caches) a new entity proxy.
 *
 * @param e
 *            Entity to cache type for.
 * @param type
 *            Entity type to proxy.
 * @return Proxy entity of type.
 *
 * @see EntityProxyHandler
 */
@SuppressWarnings("unchecked")
public <T extends Entity> T getOrNew(final Entity e, final Class<T> type) {
    final Map<Class<?>, Object> proxies = proxyMap.computeIfAbsent(e, k -> new ConcurrentHashMap<>());
    return (T) proxies.computeIfAbsent(type, k -> newEntityProxy(e, k));
}