Java Code Examples for java.util.Map.Entry#setValue()

The following examples show how to use java.util.Map.Entry#setValue() . 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: MapConstraints.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Returns a constrained view of the specified entry, using the specified
 * constraint. The {@link Entry#setValue} operation will be verified with the
 * constraint.
 *
 * @param entry the entry to constrain
 * @param constraint the constraint for the entry
 * @return a constrained view of the specified entry
 */

private static <K, V> Entry<K, V> constrainedEntry(
  final Entry<K, V> entry, final MapConstraint<? super K, ? super V> constraint) {
  checkNotNull(entry);
  checkNotNull(constraint);
  return new ForwardingMapEntry<K, V>() {
    @Override
    protected Entry<K, V> delegate() {
      return entry;
    }

    @Override
    public V setValue(V value) {
      constraint.checkKeyValue(getKey(), value);
      return entry.setValue(value);
    }
  };
}
 
Example 2
Source File: Timer.java    From ToroQuest with GNU General Public License v3.0 6 votes vote down vote up
private Runnable popRunQueue() {
	Entry<Runnable, Integer> next = null;
	for (Entry<Runnable, Integer> n : queue.entrySet()) {
		next = n;
		break;
	}

	if (next == null) {
		return null;
	}

	if (next.getValue() < 1) {
		queue.remove(next.getKey());
		return next.getKey();
	} else {
		next.setValue(next.getValue() - 1);
		return null;
	}
}
 
Example 3
Source File: MapInterfaceTest.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
public void testEntrySetSetValue() {
    // TODO: Investigate the extent to which, in practice, maps that support
    // put() also support Entry.setValue().
    if (!supportsPut || !supportsEntrySetValue) {
        return;
    }

    final Map<K, V> map;
    final V valueToSet;
    try {
        map = makePopulatedMap();
        valueToSet = getValueNotInPopulatedMap();
    } catch (UnsupportedOperationException e) {
        return;
    }

    Set<Entry<K, V>> entrySet = map.entrySet();
    Entry<K, V> entry = entrySet.iterator().next();
    final V oldValue = entry.getValue();
    final V returnedValue = entry.setValue(valueToSet);
    assertEquals(oldValue, returnedValue);
    assertTrue(entrySet.contains(
            mapEntry(entry.getKey(), valueToSet)));
    assertEquals(valueToSet, map.get(entry.getKey()));
    assertInvariants(map);
}
 
Example 4
Source File: Serialization.java    From PlayerVaults with GNU General Public License v3.0 6 votes vote down vote up
@Deprecated
private static Map<String, Object> handleSerialization(Map<String, Object> map) {
    Map<String, Object> serialized = recreateMap(map);
    for (Entry<String, Object> entry : serialized.entrySet()) {
        if (entry.getValue() instanceof ConfigurationSerializable) {
            entry.setValue(serialize((ConfigurationSerializable) entry.getValue()));
        } else if (entry.getValue() instanceof Iterable<?>) {
            List<Object> newList = new ArrayList<>();
            for (Object object : ((Iterable<?>) entry.getValue())) {
                if (object instanceof ConfigurationSerializable) {
                    object = serialize((ConfigurationSerializable) object);
                }
                newList.add(object);
            }
            entry.setValue(newList);
        } else if (entry.getValue() instanceof Map<?, ?>) {
            // unchecked cast here.  If you're serializing to a non-standard Map you deserve ClassCastExceptions
            entry.setValue(handleSerialization((Map<String, Object>) entry.getValue()));
        }
    }
    return serialized;
}
 
Example 5
Source File: ProjectBuildConfigurationComponent.java    From goclipse with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void loadDefaults() {
	if(project == null) {
		return;
	}
	
	ProjectBuildInfo buildInfo;
	try {
		buildInfo = getBuildInfo();
	} catch(CommonException e) {
		UIOperationsStatusHandler.handleStatus(true, "Error loading defaults", e);
		return;
	}
	
	for (Entry<String, BuildTargetData> entry : buildOptionsToChange) {
		String targetName = entry.getKey();
		BuildTargetData newData = buildInfo.getDefaultBuildTarget(targetName).getDataCopy(); 
		entry.setValue(newData);
	}
	handleBuildTargetChanged();
}
 
Example 6
Source File: ReadmeSimilarityCalculator.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
private HashMap<String, Integer> getAllTerms() throws IOException {
	HashMap<String, Integer> allTerms = new HashMap<>();
	int pos = 0;
	for (int docId = 0; docId < getTotalDocumentInIndex(); docId++) {
		Terms vector = getIndexReader().getTermVector(docId, FIELD_CONTENT);
		TermsEnum termsEnum = null;
		termsEnum = vector.iterator();
		BytesRef text = null;
		while ((text = termsEnum.next()) != null) {
			String term = text.utf8ToString();
			allTerms.put(term, pos++);
		}
	}

	// Update postition
	pos = 0;
	for (Entry<String, Integer> s : allTerms.entrySet()) {
		s.setValue(pos++);
	}
	return allTerms;
}
 
Example 7
Source File: Settings.java    From rtc2jira with GNU General Public License v2.0 5 votes vote down vote up
void setProperties(Properties props) {
  for (Entry<Object, Object> entry : props.entrySet()) {
    if (entry.getValue() != null) {
      entry.setValue(entry.getValue().toString().trim());
    }
  }
  this.props = props;
}
 
Example 8
Source File: DefaultAttributeMap.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public T setValue(T value) {
    final Entry<AttributeKey<T>, T> childAttr = this.childAttr;
    if (childAttr == null) {
        this.childAttr = setAttr(rootAttr.getKey(), value, false);
        return rootAttr.getValue();
    }

    final T old = childAttr.getValue();
    childAttr.setValue(value);
    return old;
}
 
Example 9
Source File: OrganizationResourceImpl.java    From apiman with Apache License 2.0 5 votes vote down vote up
/**
 * Decrypt the endpoint properties
 */
private void decryptEndpointProperties(ApiVersionBean versionBean) {
    Map<String, String> endpointProperties = versionBean.getEndpointProperties();
    if (endpointProperties != null) {
        for (Entry<String, String> entry : endpointProperties.entrySet()) {
            DataEncryptionContext ctx = new DataEncryptionContext(
                    versionBean.getApi().getOrganization().getId(),
                    versionBean.getApi().getId(),
                    versionBean.getVersion(),
                    EntityType.Api);
            entry.setValue(encrypter.decrypt(entry.getValue(), ctx));
        }
    }
}
 
Example 10
Source File: InsnListSection.java    From CodeChickenLib with GNU Lesser General Public License v2.1 5 votes vote down vote up
public Map<LabelNode, LabelNode> cloneLabels() {
    Map<LabelNode, LabelNode> labelMap = identityLabelMap();
    for(Entry<LabelNode, LabelNode> entry : labelMap.entrySet())
        entry.setValue(new LabelNode());

    return labelMap;
}
 
Example 11
Source File: DexWriter.java    From AppTroy with Apache License 2.0 5 votes vote down vote up
private void writeTypeLists(@Nonnull DexDataWriter writer) throws IOException {
    writer.align();
    typeListSectionOffset = writer.getPosition();
    for (Entry<? extends TypeListKey, Integer> entry: typeListSection.getItems()) {
        writer.align();
        entry.setValue(writer.getPosition());

        Collection<? extends TypeKey> types = typeListSection.getTypes(entry.getKey());
        writer.writeInt(types.size());
        for (TypeKey typeKey: types) {
            writer.writeUshort(typeSection.getItemIndex(typeKey));
        }
    }
}
 
Example 12
Source File: ShareVertex.java    From jstarcraft-ai with Apache License 2.0 5 votes vote down vote up
public ShareVertex(String name, MathCache factory, int numberOfShares, Layer layer, Learner learner, Normalizer normalizer) {
    super(name, factory, layer, learner, normalizer);
    this.numberOfShares = numberOfShares;
    this.vertexGradients = new HashMap<>(layer.getGradients());
    for (Entry<String, MathMatrix> term : vertexGradients.entrySet()) {
        MathMatrix matrix = term.getValue();
        matrix = factory.makeMatrix(matrix.getRowSize(), matrix.getColumnSize());
        term.setValue(matrix);
    }
}
 
Example 13
Source File: AbstractSpatialInsertGenerator.java    From liquibase-spatial with Apache License 2.0 5 votes vote down vote up
/**
 * Find any fields that look like WKT or EWKT and replace them with the database-specific value.
 */
@Override
public Sql[] generateSql(final InsertStatement statement, final Database database,
      final SqlGeneratorChain sqlGeneratorChain) {
   for (final Entry<String, Object> entry : statement.getColumnValues().entrySet()) {
      entry.setValue(handleColumnValue(entry.getValue(), database));
   }
   return super.generateSql(statement, database, sqlGeneratorChain);
}
 
Example 14
Source File: MapCategoricalTarget.java    From streaminer with Apache License 2.0 5 votes vote down vote up
@Override
protected MapCategoricalTarget mult(double multiplier) {
 for (Entry<Object, Double> categoryCount : getCounts().entrySet()) {
   categoryCount.setValue(categoryCount.getValue() * multiplier);
 }

 return this;
}
 
Example 15
Source File: Denominator.java    From denominator with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, Object> read(JsonReader in) throws IOException {
  Map<String, Object> map = delegate.read(in);
  for (Entry<String, Object> entry : map.entrySet()) {
    if (entry.getValue() instanceof Double) {
      entry.setValue(Double.class.cast(entry.getValue()).intValue());
    }
  }
  return map;
}
 
Example 16
Source File: TreeHashVector.java    From spf with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void add(final double num) {
	for (final Entry<KeyArgs, Double> entry : values.entrySet()) {
		entry.setValue(entry.getValue() + num);
	}
}
 
Example 17
Source File: MonitorCluster.java    From jlogstash-input-plugin with Apache License 2.0 4 votes vote down vote up
/**
 * 重置配置,默认都为false。
 */
private void resetChgInfo(){
	for(Entry<String, Boolean> tmp : infoChg.entrySet()){
		tmp.setValue(false);
	}
}
 
Example 18
Source File: Encodings.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Loads a list of all the supported encodings.
 *
 * System property "encodings" formatted using URL syntax may define an
 * external encodings list. Thanks to Sergey Ushakov for the code
 * contribution!
 */
private void loadEncodingInfo() {
    try {
        // load (java name)->(preferred mime name) mapping.
        final Properties props = loadProperties();

        // create instances of EncodingInfo from the loaded mapping
        Enumeration keys = props.keys();
        Map<String, EncodingInfo> canonicals = new HashMap<>();
        while (keys.hasMoreElements()) {
            final String javaName = (String) keys.nextElement();
            final String[] mimes = parseMimeTypes(props.getProperty(javaName));

            final String charsetName = findCharsetNameFor(javaName, mimes);
            if (charsetName != null) {
                final String kj = toUpperCaseFast(javaName);
                final String kc = toUpperCaseFast(charsetName);
                for (int i = 0; i < mimes.length; ++i) {
                    final String mimeName = mimes[i];
                    final String km = toUpperCaseFast(mimeName);
                    EncodingInfo info = new EncodingInfo(mimeName, charsetName);
                    _encodingTableKeyMime.put(km, info);
                    if (!canonicals.containsKey(kc)) {
                        // canonicals will map the charset name to
                        //   the info containing the prefered mime name
                        //   (the preferred mime name is the first mime
                        //   name in the list).
                        canonicals.put(kc, info);
                        _encodingTableKeyJava.put(kc, info);
                    }
                    _encodingTableKeyJava.put(kj, info);
                }
            } else {
                // None of the java or mime names on the line were
                // recognized => this charset is not supported?
            }
        }

        // Fix up the _encodingTableKeyJava so that the info mapped to
        // the java name contains the preferred mime name.
        // (a given java name can correspond to several mime name,
        //  but we want the _encodingTableKeyJava to point to the
        //  preferred mime name).
        for (Entry<String, EncodingInfo> e : _encodingTableKeyJava.entrySet()) {
            e.setValue(canonicals.get(toUpperCaseFast(e.getValue().javaName)));
        }

    } catch (java.net.MalformedURLException mue) {
        throw new com.sun.org.apache.xml.internal.serializer.utils.WrappedRuntimeException(mue);
    } catch (java.io.IOException ioe) {
        throw new com.sun.org.apache.xml.internal.serializer.utils.WrappedRuntimeException(ioe);
    }
}
 
Example 19
Source File: CommandAPI.java    From 1.13-Command-API with Apache License 2.0 4 votes vote down vote up
static void register(String commandName, CommandPermission permissions, String[] aliases, LinkedHashMap<String, Argument> args, CustomCommandExecutor executor) {
	if(!canRegister) {
		CommandAPIMain.getLog().severe("Cannot register command /" + commandName + ", because the server has finished loading!");
		return;
	}
	try {

		//Sanitize commandNames
		if(commandName == null || commandName.length() == 0) {
			throw new InvalidCommandNameException(commandName);
		}
		
		//Make a local copy of args to deal with
		@SuppressWarnings("unchecked")
		LinkedHashMap<String, Argument> copyOfArgs = args == null ? new LinkedHashMap<>() : (LinkedHashMap<String, Argument>) args.clone();
		
		//if args contains a GreedyString && args.getLast != GreedyString
		long numGreedyArgs = copyOfArgs.values().stream().filter(arg -> arg instanceof IGreedyArgument).count();
		if(numGreedyArgs >= 1) {
			//A GreedyString has been found
			if(!(copyOfArgs.values().toArray()[copyOfArgs.size() - 1] instanceof IGreedyArgument)) {
				throw new GreedyArgumentException();
			}
			
			if(numGreedyArgs > 1) {
				throw new GreedyArgumentException();
			}
		}
		
		//Reassign permissions to arguments if not declared
		for(Entry<String, Argument> entry : copyOfArgs.entrySet()) {
			if(entry.getValue().getArgumentPermission() == null) {
				entry.setValue(entry.getValue().withPermission(permissions));
			}
		}
		
		handler.register(commandName, permissions, aliases, copyOfArgs, executor);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 20
Source File: ConfigurationResolver.java    From vividus with Apache License 2.0 4 votes vote down vote up
public static ConfigurationResolver getInstance() throws IOException
{
    if (instance != null)
    {
        return instance;
    }

    PropertiesLoader propertiesLoader = new PropertiesLoader(BeanFactory.getResourcePatternResolver());

    Properties configurationProperties = propertiesLoader.loadFromSingleResource("configuration.properties");
    Properties overridingProperties = propertiesLoader.loadFromOptionalResource("overriding.properties");

    Properties properties = new Properties();
    properties.putAll(configurationProperties);
    properties.putAll(propertiesLoader.loadFromResourceTreeRecursively("defaults"));

    Multimap<String, String> configuration = assembleConfiguration(configurationProperties, overridingProperties);
    for (Entry<String, String> configurationEntry : configuration.entries())
    {
        properties.putAll(propertiesLoader.loadFromResourceTreeRecursively(configurationEntry.getKey(),
                configurationEntry.getValue()));
    }

    properties.putAll(propertiesLoader.loadFromResourceTreeRecursively(ROOT));

    Properties deprecatedProperties = propertiesLoader.loadFromResourceTreeRecursively("deprecated");
    DeprecatedPropertiesHandler deprecatedPropertiesHandler = new DeprecatedPropertiesHandler(
            deprecatedProperties, PLACEHOLDER_PREFIX, PLACEHOLDER_SUFFIX);
    deprecatedPropertiesHandler.replaceDeprecated(properties);

    Properties overridingAndSystemProperties = new Properties();
    overridingAndSystemProperties.putAll(overridingProperties);
    overridingAndSystemProperties.putAll(System.getenv());
    overridingAndSystemProperties.putAll(loadFilteredSystemProperties());

    deprecatedPropertiesHandler.replaceDeprecated(overridingAndSystemProperties, properties);

    properties.putAll(overridingAndSystemProperties);

    resolveSpelExpressions(properties, true);

    PropertyPlaceholderHelper propertyPlaceholderHelper = createPropertyPlaceholderHelper(false);

    for (Entry<Object, Object> entry : properties.entrySet())
    {
        String key = (String) entry.getKey();
        String value = (String) entry.getValue();
        deprecatedPropertiesHandler.warnIfDeprecated(key, value);
        entry.setValue(propertyPlaceholderHelper.replacePlaceholders(value, properties::getProperty));
    }
    deprecatedPropertiesHandler.removeDeprecated(properties);
    resolveSpelExpressions(properties, false);
    processSystemProperties(properties);

    instance = new ConfigurationResolver(properties);
    return instance;
}