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

The following examples show how to use java.util.HashMap#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: InsertFromValues.java    From crate with Apache License 2.0 6 votes vote down vote up
private void checkConstraintsOnGeneratedSource(Object[] cells,
                                               String indexName,
                                               DocTableInfo tableInfo,
                                               PlannerContext plannerContext,
                                               HashMap<String, InsertSourceFromCells> validatorsCache) throws Throwable {
    var validator = validatorsCache.computeIfAbsent(
        indexName,
        index -> new InsertSourceFromCells(
            plannerContext.transactionContext(),
            plannerContext.functions(),
            tableInfo,
            index,
            GeneratedColumns.Validation.VALUE_MATCH,
            writerProjection.allTargetColumns()));
    validator.generateSourceAndCheckConstraints(cells);
}
 
Example 2
Source File: SqlRecorderRuntime.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Map<String, List<SqlRecord>> getRecordList() {
    HashMap<String, LinkedList<SqlRecord>> map = new HashMap<>();
    for (RecordContext recordContext : all) {
        for (Map.Entry<String, SqlRecord[]> stringEntry : recordContext.map.entrySet()) {
            String statement = stringEntry.getKey();
            LinkedList<SqlRecord> resList = map.computeIfAbsent(statement, s -> new LinkedList<SqlRecord>());
            for (SqlRecord record : stringEntry.getValue()) {
                if (record.getStatement() != null) {
                    resList.add(record);
                }
            }
        }
    }
    return (Map) map;
}
 
Example 3
Source File: StreamingJobGraphGenerator.java    From flink with Apache License 2.0 5 votes vote down vote up
private void setSlotSharingAndCoLocation() {
	final HashMap<String, SlotSharingGroup> slotSharingGroups = new HashMap<>();
	final HashMap<String, Tuple2<SlotSharingGroup, CoLocationGroup>> coLocationGroups = new HashMap<>();

	for (Entry<Integer, JobVertex> entry : jobVertices.entrySet()) {

		final StreamNode node = streamGraph.getStreamNode(entry.getKey());
		final JobVertex vertex = entry.getValue();

		// configure slot sharing group
		final String slotSharingGroupKey = node.getSlotSharingGroup();
		final SlotSharingGroup sharingGroup;

		if (slotSharingGroupKey != null) {
			sharingGroup = slotSharingGroups.computeIfAbsent(
					slotSharingGroupKey, (k) -> new SlotSharingGroup());
			vertex.setSlotSharingGroup(sharingGroup);
		} else {
			sharingGroup = null;
		}

		// configure co-location constraint
		final String coLocationGroupKey = node.getCoLocationGroup();
		if (coLocationGroupKey != null) {
			if (sharingGroup == null) {
				throw new IllegalStateException("Cannot use a co-location constraint without a slot sharing group");
			}

			Tuple2<SlotSharingGroup, CoLocationGroup> constraint = coLocationGroups.computeIfAbsent(
					coLocationGroupKey, (k) -> new Tuple2<>(sharingGroup, new CoLocationGroup()));

			if (constraint.f0 != sharingGroup) {
				throw new IllegalStateException("Cannot co-locate operators from different slot sharing groups");
			}

			vertex.updateCoLocationGroup(constraint.f1);
			constraint.f1.addVertex(vertex);
		}
	}
}
 
Example 4
Source File: ProcessInstanceMigrationManagerImpl.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected static void splitMigrationMappingByCallActivitySubProcessScope(ActivityMigrationMapping activityMigrationMapping, HashMap<String, ActivityMigrationMapping> mainProcessActivityMappingByFromActivityId, HashMap<String, HashMap<String, ActivityMigrationMapping>> subProcessActivityMappingsByCallActivityIdAndFromActivityId) {
    HashMap<String, ActivityMigrationMapping> mapToFill;
    if (activityMigrationMapping.isToParentProcess()) {
        mapToFill = subProcessActivityMappingsByCallActivityIdAndFromActivityId.computeIfAbsent(activityMigrationMapping.getFromCallActivityId(), k -> new HashMap<>());
    } else {
        mapToFill = mainProcessActivityMappingByFromActivityId;
    }
    for (String fromActivityId : activityMigrationMapping.getFromActivityIds()) {
        mapToFill.put(fromActivityId, activityMigrationMapping);
    }
}
 
Example 5
Source File: ScencoExecutionSupport.java    From workcraft with MIT License 5 votes vote down vote up
protected void groupConstraints(int n, int m, char[][][] constraints, HashMap<String, Integer> task) {
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (trivialEncoding(constraints, m, i, j) == '?') {
                String constraint = generateConstraint(constraints, m, i, j);
                task.computeIfAbsent(constraint, s -> task.size());
            }
        }
    }
}
 
Example 6
Source File: MCRCategLinkServiceImpl.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void deleteLinks(final Collection<MCRCategLinkReference> ids) {
    if (ids.isEmpty()) {
        return;
    }
    HashMap<String, Collection<String>> typeMap = new HashMap<>();
    //prepare
    Collection<String> objectIds = new LinkedList<>();
    String currentType = ids.iterator().next().getType();
    typeMap.put(currentType, objectIds);
    //collect per type
    for (MCRCategLinkReference ref : ids) {
        if (!currentType.equals(ref.getType())) {
            currentType = ref.getType();
            objectIds = typeMap.computeIfAbsent(ref.getType(), k -> new LinkedList<>());
        }
        objectIds.add(ref.getObjectID());
    }
    EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
    javax.persistence.Query q = em.createNamedQuery(NAMED_QUERY_NAMESPACE + "deleteByObjectCollection");
    int deleted = 0;
    for (Map.Entry<String, Collection<String>> entry : typeMap.entrySet()) {
        q.setParameter("ids", entry.getValue());
        q.setParameter("type", entry.getKey());
        deleted += q.executeUpdate();
    }
    LOGGER.debug("Number of Links deleted: {}", deleted);
}
 
Example 7
Source File: ResourcePackManager.java    From AdditionsAPI with MIT License 5 votes vote down vote up
private static ItemModel getOrCreateItemModel(HashMap<DamageableItem, ItemModel> itemModels,
		final DamageableItem baseItem) {
	return itemModels.computeIfAbsent(baseItem, new Function<DamageableItem, ItemModel>() {
		@Override
		public ItemModel apply(DamageableItem k) {
			return baseItem.getDefaultItemModel();
		}
	});
}
 
Example 8
Source File: RealTimeCollisionTile.java    From Runescape-Web-Walker-Engine with Apache License 2.0 5 votes vote down vote up
public static RealTimeCollisionTile create(int x, int y, int z, int collision){
    RealTimeCollisionTile realTimeCollisionTile = new RealTimeCollisionTile(x, y, z, collision);
    if (!realTimeCollisionTile.isInitialized()){
        return null;
    }
    HashMap<Integer, HashMap<Integer, RealTimeCollisionTile>> yMap = xMap.computeIfAbsent(realTimeCollisionTile.getX(), k -> new HashMap<>());
    HashMap<Integer, RealTimeCollisionTile> zMap = yMap.computeIfAbsent(realTimeCollisionTile.getY(), k -> new HashMap<>());
    zMap.put(realTimeCollisionTile.getZ(), realTimeCollisionTile);
    allCached.add(realTimeCollisionTile);
    return realTimeCollisionTile;
}
 
Example 9
Source File: ChakraTest.java    From es6draft with MIT License 5 votes vote down vote up
private static BiFunction<Path, Path, ChakraTestInfo> createTestFunction() {
    HashMap<Path, Map<String, TestSetting>> settingsMapping = new HashMap<>();

    return (basedir, file) -> {
        ChakraTestInfo testInfo = new ChakraTestInfo(basedir, file);
        Path dir = basedir.resolve(file).getParent();
        Map<String, TestSetting> map = settingsMapping.computeIfAbsent(dir, ChakraTest::readSettings);
        TestSetting setting = map.get(file.getFileName().toString());
        if (setting != null) {
            testInfo.baseline = setting.baseline;
            testInfo.setEnabled(!setting.disabled);
        }
        return testInfo;
    };
}
 
Example 10
Source File: CapabilitiesTypeDecoder.java    From arctic-sea with Apache License 2.0 5 votes vote down vote up
private Map<String, Set<String>> parseRelatedFeatures(ObservationOfferingType obsOff) {
    HashMap<String, Set<String>> map = new HashMap<>(obsOff.getRelatedFeatureArray().length);
    for (RelatedFeature releatedFeature : obsOff.getRelatedFeatureArray()) {
        String feature = releatedFeature.getFeatureRelationship().getTarget().getHref();
        String role = releatedFeature.getFeatureRelationship().getRole();
        Set<String> roles = map.computeIfAbsent(feature, key -> new HashSet<>(1));
        if (role != null) {
            roles.add(role);
        }
    }
    return map;
}
 
Example 11
Source File: MultiCurrencyAmountArray.java    From Strata with Apache License 2.0 5 votes vote down vote up
/**
 * Obtains an instance from the specified multi-currency amounts.
 *
 * @param amounts  the amounts
 * @return an instance with the specified amounts
 */
public static MultiCurrencyAmountArray of(List<MultiCurrencyAmount> amounts) {
  int size = amounts.size();
  HashMap<Currency, double[]> valueMap = new HashMap<>();
  for (int i = 0; i < size; i++) {
    MultiCurrencyAmount multiCurrencyAmount = amounts.get(i);
    for (CurrencyAmount currencyAmount : multiCurrencyAmount.getAmounts()) {
      double[] currencyValues = valueMap.computeIfAbsent(currencyAmount.getCurrency(), ccy -> new double[size]);
      currencyValues[i] = currencyAmount.getAmount();
    }
  }
  Map<Currency, DoubleArray> doubleArrayMap = MapStream.of(valueMap).mapValues(v -> DoubleArray.ofUnsafe(v)).toMap();
  return new MultiCurrencyAmountArray(size, doubleArrayMap);
}
 
Example 12
Source File: HeapGraph.java    From jheappo with Apache License 2.0 5 votes vote down vote up
private Node mergeNode(GraphDatabaseService db, HashMap<Long, Node> cache, Labels type, long objectId) {

        return cache.computeIfAbsent(objectId, (id) -> {
            Node n = db.createNode(type);
            n.setProperty("id", id);
            return n;
        });
    }
 
Example 13
Source File: TestdataStatement.java    From neodymium-library with MIT License 4 votes vote down vote up
private List<Object> processDuplicates(List<Object> iterations)
{
    // since the user can decide to annotate the same data set several times to the same function we need to care
    // about the duplicates. First of all we need to clone those objects, then we need to set a special index which
    // will be later used to distinguish them in the run

    // this map contains the counter for the new index
    HashMap<Object, Integer> iterationIndexMap = new HashMap<>();
    List<Object> fixedIterations = new LinkedList<>();

    for (Object object : iterations)
    {
        if (!fixedIterations.contains(object))
        {
            // no duplicate, just add it
            fixedIterations.add(object);
        }
        else
        {
            // now the funny part, we encountered an duplicated object

            // always set the first occurrence of an object to 1
            TestdataStatementData existingObject = (TestdataStatementData) object;
            existingObject.setIterationIndex(1);

            // set the counter for this object to 1
            iterationIndexMap.computeIfAbsent(object, (o) -> {
                return 1;
            });

            // increment the counter every time we visit with the same object
            Integer newIndex = iterationIndexMap.computeIfPresent(object, (o, index) -> {
                return (index + 1);
            });

            // important: we clone that object
            TestdataStatementData clonedObject = new TestdataStatementData((TestdataStatementData) object);
            // set the "iteration" index to the new cloned object
            clonedObject.setIterationIndex(newIndex);
            // add it to the list
            fixedIterations.add(clonedObject);
        }
    }

    return fixedIterations;
}
 
Example 14
Source File: DuplicateBranches.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void updateMap(HashMap<BigInteger, Collection<Integer>> map, int i, BigInteger clauseAsInt) {
    Collection<Integer> values = map.computeIfAbsent(clauseAsInt, k -> new LinkedList<>());

    values.add(i); // index into the sorted array
}
 
Example 15
Source File: memoizer4.java    From design-pattern-reloaded with MIT License 4 votes vote down vote up
static <V, R> Function<V, R> memoize(BiFunction<? super V, Function<? super V, ? extends R>, ? extends R> fun) {
  HashMap<V, R> map = new HashMap<>();
  @SuppressWarnings("unchecked")
  Function<V, R>[] memoizer = (Function<V, R>[])new Function<?, ?>[1];
  return memoizer[0] = value -> map.computeIfAbsent(value, v -> fun.apply(v, memoizer[0]));
}
 
Example 16
Source File: StreamingJobGraphGenerator.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
private void setSlotSharingAndCoLocation() {
	final HashMap<String, SlotSharingGroup> slotSharingGroups = new HashMap<>();
	final HashMap<String, Tuple2<SlotSharingGroup, CoLocationGroup>> coLocationGroups = new HashMap<>();

	for (Entry<Integer, JobVertex> entry : jobVertices.entrySet()) {

		final StreamNode node = streamGraph.getStreamNode(entry.getKey());
		final JobVertex vertex = entry.getValue();

		// configure slot sharing group
		final String slotSharingGroupKey = node.getSlotSharingGroup();
		final SlotSharingGroup sharingGroup;

		if (slotSharingGroupKey != null) {
			sharingGroup = slotSharingGroups.computeIfAbsent(
					slotSharingGroupKey, (k) -> new SlotSharingGroup());
			vertex.setSlotSharingGroup(sharingGroup);
		} else {
			sharingGroup = null;
		}

		// configure co-location constraint
		final String coLocationGroupKey = node.getCoLocationGroup();
		if (coLocationGroupKey != null) {
			if (sharingGroup == null) {
				throw new IllegalStateException("Cannot use a co-location constraint without a slot sharing group");
			}

			Tuple2<SlotSharingGroup, CoLocationGroup> constraint = coLocationGroups.computeIfAbsent(
					coLocationGroupKey, (k) -> new Tuple2<>(sharingGroup, new CoLocationGroup()));

			if (constraint.f0 != sharingGroup) {
				throw new IllegalStateException("Cannot co-locate operators from different slot sharing groups");
			}

			vertex.updateCoLocationGroup(constraint.f1);
		}
	}

	for (Tuple2<StreamNode, StreamNode> pair : streamGraph.getIterationSourceSinkPairs()) {

		CoLocationGroup ccg = new CoLocationGroup();

		JobVertex source = jobVertices.get(pair.f0.getId());
		JobVertex sink = jobVertices.get(pair.f1.getId());

		ccg.addVertex(source);
		ccg.addVertex(sink);
		source.updateCoLocationGroup(ccg);
		sink.updateCoLocationGroup(ccg);
	}

}
 
Example 17
Source File: builder5.java    From design-pattern-reloaded with MIT License 4 votes vote down vote up
static <K, T> Function<K, T> factoryKit(Consumer<BiConsumer<K, T>> consumer, Function<? super K, ? extends T> ifAbsent) {
  HashMap<K, T> map = new HashMap<>();
  consumer.accept(map::put);
  return key -> map.computeIfAbsent(key, ifAbsent);
}
 
Example 18
Source File: memoizer5.java    From design-pattern-reloaded with MIT License 4 votes vote down vote up
static <V, R> Function<V, R> memoize(BiFunction<? super V, Function<? super V, ? extends R>, ? extends R> fun) {
  HashMap<V, R> map = new HashMap<>();
  return new Object() {
    Function<V, R> memoizer = value -> map.computeIfAbsent(value, v -> fun.apply(v, this.memoizer));
  }.memoizer;
}
 
Example 19
Source File: curry3.java    From design-pattern-reloaded with MIT License 4 votes vote down vote up
static <K, T> Function<K, T> factory(Consumer<BiConsumer<K, T>> consumer, Function<? super K, ? extends T> ifAbsent) {
  HashMap<K, T> map = new HashMap<>();
  consumer.accept(map::put);
  return key -> map.computeIfAbsent(key, ifAbsent);
}
 
Example 20
Source File: WorldGenFromFile.java    From rogue-cloud with Apache License 2.0 2 votes vote down vote up
/** Add random candlesticks in all the given homes. 
 * @throws InterruptedException */
private static void addCandleSticks(List<DrawRoomResult> houses, RCArrayMap aMap) throws InterruptedException {
	
	TileType[] validFloorSurfaces = TileTypeList.ALL_COBBLESTONE;
	
	Random r = new Random();
	
	final int TOTAL_ROOM_ATTEMPTS = 1000;
	
	HashMap<DrawRoomResult, List<Position>> roomTorches = new HashMap<>();
	
	// Draw torches 
	for(int count = 0; count < TOTAL_ROOM_ATTEMPTS; count++) {
		
		DrawRoomResult drr = houses.get(r.nextInt(houses.size()));
		
		List<Position> previousTorches = roomTorches.computeIfAbsent(drr, k -> new ArrayList<Position>() );
		if(previousTorches.size() > 4) { continue; }
		
		Position p = doSearch(drr, aMap, r, 100, (int xPos, int yPos, IMap map) -> {
			
			if(shortestManhattanDistanceToPreviousPositions(xPos, yPos, previousTorches) < 5) {
				return false;
			}
			
			Tile posTile = map.getTile(xPos, yPos);
			
			// top tile must a valid torch surface
			return AcontainsAtLeastOneB(new TileType[] { posTile.getTileTypeLayers()[0] }, validFloorSurfaces );
			
		});
		
		if(p != null) {
			
			stampTileOntoMap(p.getX(), p.getY(), TileTypeList.CANDLE_STICK, true, aMap);				
			previousTorches.add(p);
		}
		
		if(count % 20 == 0) { assertNotInterrupted(); }
	} // end for
	
	roomTorches = null;
	
}