下面列出了java.util.HashMap#computeIfAbsent ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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;
}
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);
}
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);
}
}
}
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;
});
}
/**
* 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);
}
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;
}
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;
};
}
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;
}
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();
}
});
}
@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);
}
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());
}
}
}
}
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);
}
}
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);
}
}
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;
}
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
}
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]));
}
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);
}
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;
}
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);
}
/** 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;
}