Java Code Examples for java.util.Map#Entry

The following examples show how to use java.util.Map#Entry . 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: LiteralElement.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * This method starts at a given node, traverses all namespace mappings,
 * and assembles a list of all prefixes that (for the given node) maps
 * to _ANY_ namespace URI. Used by literal result elements to determine
 */
public Set<Map.Entry<String, String>> getNamespaceScope(SyntaxTreeNode node) {
    Map<String, String> all = new HashMap<>();

    while (node != null) {
        Map<String, String> mapping = node.getPrefixMapping();
        if (mapping != null) {
            for( String prefix : mapping.keySet()) {
                if (!all.containsKey(prefix)) {
                    all.put(prefix, mapping.get(prefix));
                }
            }
        }
        node = node.getParent();
    }
    return all.entrySet();
}
 
Example 2
Source File: DefaultRheaKVStore.java    From sofa-jraft with Apache License 2.0 6 votes vote down vote up
private FutureGroup<Map<ByteArray, byte[]>> internalMultiGet(final List<byte[]> keys, final boolean readOnlySafe,
                                                             final int retriesLeft, final Throwable lastCause) {
    final Map<Region, List<byte[]>> regionMap = this.pdClient
            .findRegionsByKeys(keys, ApiExceptionHelper.isInvalidEpoch(lastCause));
    final List<CompletableFuture<Map<ByteArray, byte[]>>> futures = Lists.newArrayListWithCapacity(regionMap.size());
    final Errors lastError = lastCause == null ? null : Errors.forException(lastCause);
    for (final Map.Entry<Region, List<byte[]>> entry : regionMap.entrySet()) {
        final Region region = entry.getKey();
        final List<byte[]> subKeys = entry.getValue();
        final RetryCallable<Map<ByteArray, byte[]>> retryCallable = retryCause -> internalMultiGet(subKeys,
                readOnlySafe, retriesLeft - 1, retryCause);
        final MapFailoverFuture<ByteArray, byte[]> future = new MapFailoverFuture<>(retriesLeft, retryCallable);
        internalRegionMultiGet(region, subKeys, readOnlySafe, future, retriesLeft, lastError, this.onlyLeaderRead);
        futures.add(future);
    }
    return new FutureGroup<>(futures);
}
 
Example 3
Source File: Statement.java    From enmasse with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new SQL statement instance.
 * <p>
 * This will parse the SQL statement for named parameters, and record the information for expanding
 * it later on.
 *
 * @param sql The SQL statement to process.
 * @return The statement, or {@code null} if the provided SQL as {@code null}.
 */
public static Statement statement(final String sql, final Object... values) {
    if (sql == null) {
        return null;
    }

    final String sqlFormatted = String.format(sql, values);

    final Pattern pattern = DEFAULT_PATTERN;
    final Matcher m = pattern.matcher(sqlFormatted);

    int idx = 0;
    final StringBuilder sb = new StringBuilder();
    final List<Map.Entry<String, Integer>> mappings = new ArrayList<>();
    while (m.find()) {
        m.appendReplacement(sb, "${pre}?");
        mappings.add(new SimpleImmutableEntry<>(m.group("name"), idx));
        idx++;
    }
    m.appendTail(sb);

    return new Statement(sb.toString(), mappings);
}
 
Example 4
Source File: HttpHeaders.java    From okhttp-OkGo with Apache License 2.0 5 votes vote down vote up
public final String toJSONString() {
    JSONObject jsonObject = new JSONObject();
    try {
        for (Map.Entry<String, String> entry : headersMap.entrySet()) {
            jsonObject.put(entry.getKey(), entry.getValue());
        }
    } catch (JSONException e) {
        OkLogger.printStackTrace(e);
    }
    return jsonObject.toString();
}
 
Example 5
Source File: OpenIntToDoubleHashMapTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void testRemove() {
    OpenIntToDoubleHashMap map = createFromJavaMap();
    int mapSize = javaMap.size();
    assertEquals(mapSize, map.size());
    for (Map.Entry<Integer, Double> mapEntry : javaMap.entrySet()) {
        map.remove(mapEntry.getKey());
        assertEquals(--mapSize, map.size());
        assertTrue(Double.isNaN(map.get(mapEntry.getKey())));
    }

    /* Ensure that put and get still work correctly after removals */
    assertPutAndGet(map);
}
 
Example 6
Source File: FieldSelector.java    From android-places-demos with Apache License 2.0 5 votes vote down vote up
/**
 * Returns all {@link Field} values the user selected.
 */
public List<Field> getSelectedFields() {
  List<Field> selectedList = new ArrayList<>();
  for (Map.Entry<Field, State> entry : fieldStates.entrySet()) {
    if (entry.getValue().checked) {
      selectedList.add(entry.getKey());
    }
  }

  return selectedList;
}
 
Example 7
Source File: BrokerData.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
public String selectBrokerAddr() {
    String value = this.brokerAddrs.get(MixAll.MASTER_ID);
    if (null == value) {
        for (Map.Entry<Long, String> entry : this.brokerAddrs.entrySet()) {
            return entry.getValue();
        }
    }

    return value;
}
 
Example 8
Source File: TObjectIntHashMapDecorator.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
    * Copies the key/value mappings in <tt>map</tt> into this map.
    * Note that this will be a <b>deep</b> copy, as storage is by
    * primitive value.
    *
    * @param map a <code>Map</code> value
    */
   @Override // GemStoneAddition
   public void putAll(Map map) {
Iterator it = map.entrySet().iterator();
for (int i = map.size(); i-- > 0;) {
    Map.Entry e = (Map.Entry)it.next();
    this.put(e.getKey(), e.getValue());
}
   }
 
Example 9
Source File: HashMap.java    From mts with GNU General Public License v3.0 5 votes vote down vote up
public boolean contains(Object o) {
    if (!(o instanceof Map.Entry))
        return false;
    Map.Entry<K,V> e = (Map.Entry<K,V>) o;
    Entry<K,V> candidate = getEntry(e.getKey());
    return candidate != null && candidate.equals(e);
}
 
Example 10
Source File: Analyze.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/** Identifies entities in the contents of the object at the given GCS {@code path}. */
public static void analyzeEntitiesFile(String gcsUri) throws Exception {
  // [START language_entities_gcs]
  // Instantiate the Language client com.google.cloud.language.v1.LanguageServiceClient
  try (LanguageServiceClient language = LanguageServiceClient.create()) {
    // set the GCS Content URI path to the file to be analyzed
    Document doc =
        Document.newBuilder().setGcsContentUri(gcsUri).setType(Type.PLAIN_TEXT).build();
    AnalyzeEntitiesRequest request =
        AnalyzeEntitiesRequest.newBuilder()
            .setDocument(doc)
            .setEncodingType(EncodingType.UTF16)
            .build();

    AnalyzeEntitiesResponse response = language.analyzeEntities(request);

    // Print the response
    for (Entity entity : response.getEntitiesList()) {
      System.out.printf("Entity: %s\n", entity.getName());
      System.out.printf("Salience: %.3f\n", entity.getSalience());
      System.out.println("Metadata: ");
      for (Map.Entry<String, String> entry : entity.getMetadataMap().entrySet()) {
        System.out.printf("%s : %s", entry.getKey(), entry.getValue());
      }
      for (EntityMention mention : entity.getMentionsList()) {
        System.out.printf("Begin offset: %d\n", mention.getText().getBeginOffset());
        System.out.printf("Content: %s\n", mention.getText().getContent());
        System.out.printf("Type: %s\n\n", mention.getType());
      }
    }
  }
  // [END language_entities_gcs]
}
 
Example 11
Source File: LazyAttributesMetadata.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Build a LazyFetchGroupMetadata based on the attributes defined for the
 * PersistentClass
 *
 * @param mappedEntity The entity definition
 *
 * @return The built LazyFetchGroupMetadata
 */
public static LazyAttributesMetadata from(PersistentClass mappedEntity) {
	final Map<String, LazyAttributeDescriptor> lazyAttributeDescriptorMap = new LinkedHashMap<>();
	final Map<String, Set<String>> fetchGroupToAttributesMap = new HashMap<>();

	int i = -1;
	int x = 0;
	final Iterator itr = mappedEntity.getPropertyClosureIterator();
	while ( itr.hasNext() ) {
		i++;
		final Property property = (Property) itr.next();
		if ( property.isLazy() ) {
			final LazyAttributeDescriptor lazyAttributeDescriptor = LazyAttributeDescriptor.from( property, i, x++ );
			lazyAttributeDescriptorMap.put( lazyAttributeDescriptor.getName(), lazyAttributeDescriptor );

			final Set<String> attributeSet = fetchGroupToAttributesMap.computeIfAbsent(
					lazyAttributeDescriptor.getFetchGroupName(),
					k -> new LinkedHashSet<>()
			);
			attributeSet.add( lazyAttributeDescriptor.getName() );
		}
	}

	if ( lazyAttributeDescriptorMap.isEmpty() ) {
		return new LazyAttributesMetadata( mappedEntity.getEntityName() );
	}

	for ( Map.Entry<String, Set<String>> entry : fetchGroupToAttributesMap.entrySet() ) {
		entry.setValue( Collections.unmodifiableSet( entry.getValue() ) );
	}

	return new LazyAttributesMetadata(
			mappedEntity.getEntityName(),
			Collections.unmodifiableMap( lazyAttributeDescriptorMap ),
			Collections.unmodifiableMap( fetchGroupToAttributesMap )
	);
}
 
Example 12
Source File: EntrySet.java    From adaptive-radix-tree with MIT License 5 votes vote down vote up
@Override
public boolean contains(Object o) {
	if (!(o instanceof Map.Entry))
		return false;
	Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o;
	Object value = entry.getValue();
	LeafNode<K, V> p = m.getEntry(entry.getKey());
	return p != null && AdaptiveRadixTree.valEquals(p.getValue(), value);
}
 
Example 13
Source File: OpenIntToFieldTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void testPutAbsentOnExisting() {
    OpenIntToFieldHashMap<Fraction> map = createFromJavaMap(field);
    int size = javaMap.size();
    for (Map.Entry<Integer, Fraction> mapEntry : generateAbsent().entrySet()) {
        map.put(mapEntry.getKey(), mapEntry.getValue());
        assertEquals(++size, map.size());
        assertEquals(mapEntry.getValue(), map.get(mapEntry.getKey()));
    }
}
 
Example 14
Source File: CommandUtils.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public static Object executeCommand( String commandId, Map paramMap )
		throws NotDefinedException, ExecutionException,
		ParameterValueConversionException, NotEnabledException,
		NotHandledException
{
	Command cmd = CommandUtils.getCommand( commandId );
	List paramList = new ArrayList( );
	if ( paramMap != null )
	{
		for ( Iterator iter = paramMap.entrySet( ).iterator( ); iter.hasNext( ); )
		{
			Map.Entry entry = (Entry) iter.next( );
			String paramId = entry.getKey( ).toString( );
			Object value = entry.getValue( );
			if ( value != null )
			{
				paramList.add( createParameter( cmd, paramId, value ) );
			}
		}
	}
	if ( paramList.size( ) > 0 )
	{
		ParameterizedCommand paramCommand = new ParameterizedCommand( cmd,
				(Parameterization[]) paramList.toArray( new Parameterization[paramList.size( )] ) );

		return getHandlerService( ).executeCommand( paramCommand, null );
	}
	else
	{
		return getHandlerService( ).executeCommand( commandId, null );
	}
}
 
Example 15
Source File: SplitNodeHandler.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public void writeNode(Node node, StringBuilder xmlDump, boolean includeMeta) {
	Split splitNode = (Split) node;
	writeNode("split", splitNode, xmlDump, includeMeta);
       int type = splitNode.getType();
       if (type != 0) {
           xmlDump.append("type=\"" + type + "\" ");
       }
       if (splitNode.getConstraints().isEmpty()) {
           endNode(xmlDump);
       } else {
           xmlDump.append(">" + EOL);
           if (includeMeta) {
           	writeMetaData(splitNode, xmlDump);
           }
           xmlDump.append("      <constraints>" + EOL);
           for (Map.Entry<ConnectionRef, Constraint> entry: splitNode.getConstraints().entrySet()) {
               ConnectionRef connection = entry.getKey();
               Constraint constraint = entry.getValue();
               xmlDump.append("        <constraint "
                   + "toNodeId=\"" + connection.getNodeId() + "\" "
                   + "toType=\"" + connection.getToType() + "\" ");
               String name = constraint.getName();
               if (name != null && !"".equals(name)) {
                   xmlDump.append("name=\"" + XmlDumper.replaceIllegalChars(constraint.getName()) + "\" ");
               }
               int priority = constraint.getPriority();
               if (priority != 0) {
                   xmlDump.append("priority=\"" + constraint.getPriority() + "\" ");
               }
               xmlDump.append("type=\"" + constraint.getType() + "\" ");
               String dialect = constraint.getDialect();
               if (dialect != null && !"".equals(dialect)) {
                   xmlDump.append("dialect=\"" + dialect + "\" ");
               }
               String constraintString = constraint.getConstraint();
               if (constraintString != null) {
                   xmlDump.append(">" + XmlDumper.replaceIllegalChars(constraintString) + "</constraint>" + EOL);
               } else {
                   xmlDump.append("/>" + EOL);
               }
           }
           xmlDump.append("      </constraints>" + EOL);
           endNode("split", xmlDump);
       }
}
 
Example 16
Source File: ToGeoFunction.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public static void register(ScalarFunctionModule module) {
    for (Map.Entry<DataType, String> function : CastFunctionResolver.GEO_FUNCTION_MAP.entrySet()) {
        module.register(function.getValue(), new GeoResolver(function.getKey(), function.getValue()));
    }
}
 
Example 17
Source File: TestFeedParser.java    From anthelion with Apache License 2.0 4 votes vote down vote up
/**
 * Calls the {@link FeedParser} on a sample RSS file and checks that there are
 * 3 {@link ParseResult} entries including the below 2 links:
 * <ul>
 * <li>http://www-scf.usc.edu/~mattmann/</li>
 * <li>http://www.nutch.org</li>
 * </ul>
 * 
 * 
 * @throws ProtocolNotFound
 *           If the {@link Protocol}Layer cannot be loaded (required to fetch
 *           the {@link Content} for the RSS file).
 * @throws ParseException
 *           If the {@link Parser}Layer cannot be loaded.
 */
public void testParseFetchChannel() throws ProtocolNotFound, ParseException {
  String urlString;
  Protocol protocol;
  Content content;
  ParseResult parseResult;

  Configuration conf = NutchConfiguration.create();
  for (int i = 0; i < sampleFiles.length; i++) {
    urlString = "file:" + sampleDir + fileSeparator + sampleFiles[i];
    urlString = urlString.replace('\\', '/');

    protocol = new ProtocolFactory(conf).getProtocol(urlString);
    content = protocol.getProtocolOutput(new Text(urlString),
        new CrawlDatum()).getContent();

    parseResult = new ParseUtil(conf).parseByExtensionId("feed", content);

    assertEquals(3, parseResult.size());

    boolean hasLink1 = false, hasLink2 = false, hasLink3=false;

    for (Iterator<Map.Entry<Text, Parse>> j = parseResult.iterator(); j
        .hasNext();) {
      Map.Entry<Text, Parse> entry = j.next();
      if (entry.getKey().toString().equals(
          "http://www-scf.usc.edu/~mattmann/")) {
        hasLink1 = true;
      } else if (entry.getKey().toString().equals("http://www.nutch.org/")) {
        hasLink2 = true;
      }
      else if(entry.getKey().toString().equals(urlString)){
        hasLink3 = true;
      }

      assertNotNull(entry.getValue());
      assertNotNull(entry.getValue().getData());
    }

    if (!hasLink1 || !hasLink2 || !hasLink3) {
      fail("Outlinks read from sample rss file are not correct!");
    }
  }

}
 
Example 18
Source File: CommandDescriptor.java    From incubator-retired-blur with Apache License 2.0 4 votes vote down vote up
@Override
public void write(org.apache.blur.thirdparty.thrift_0_9_0.protocol.TProtocol prot, CommandDescriptor struct) throws org.apache.blur.thirdparty.thrift_0_9_0.TException {
  TTupleProtocol oprot = (TTupleProtocol) prot;
  BitSet optionals = new BitSet();
  if (struct.isSetCommandName()) {
    optionals.set(0);
  }
  if (struct.isSetDescription()) {
    optionals.set(1);
  }
  if (struct.isSetRequiredArguments()) {
    optionals.set(2);
  }
  if (struct.isSetOptionalArguments()) {
    optionals.set(3);
  }
  if (struct.isSetReturnType()) {
    optionals.set(4);
  }
  if (struct.isSetVersion()) {
    optionals.set(5);
  }
  oprot.writeBitSet(optionals, 6);
  if (struct.isSetCommandName()) {
    oprot.writeString(struct.commandName);
  }
  if (struct.isSetDescription()) {
    oprot.writeString(struct.description);
  }
  if (struct.isSetRequiredArguments()) {
    {
      oprot.writeI32(struct.requiredArguments.size());
      for (Map.Entry<String, ArgumentDescriptor> _iter300 : struct.requiredArguments.entrySet())
      {
        oprot.writeString(_iter300.getKey());
        _iter300.getValue().write(oprot);
      }
    }
  }
  if (struct.isSetOptionalArguments()) {
    {
      oprot.writeI32(struct.optionalArguments.size());
      for (Map.Entry<String, ArgumentDescriptor> _iter301 : struct.optionalArguments.entrySet())
      {
        oprot.writeString(_iter301.getKey());
        _iter301.getValue().write(oprot);
      }
    }
  }
  if (struct.isSetReturnType()) {
    oprot.writeString(struct.returnType);
  }
  if (struct.isSetVersion()) {
    oprot.writeString(struct.version);
  }
}
 
Example 19
Source File: SoftCache.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
Entry(Map.Entry ent, Object value) {
    this.ent = ent;
    this.value = value;
}
 
Example 20
Source File: CacheLoaderWriter.java    From ehcache3 with Apache License 2.0 2 votes vote down vote up
/**
 * Writes multiple mappings.
 * <p>
 * The writes may represent a mix of brand new values and updates to existing values.
 * <p>
 * By using a {@link BulkCacheWritingException} implementors can report partial success. Any other exception will
 * be thrown back to the {@code Cache} user through a {@link BulkCacheWritingException} indicating a complete failure.
 *
 * @param entries the mappings to write
 *
 * @throws BulkCacheWritingException in case of partial success
 * @throws Exception in case no values could be written
 */
default void writeAll(Iterable<? extends Map.Entry<? extends K, ? extends V>> entries) throws BulkCacheWritingException, Exception {
  for (Map.Entry<? extends K, ? extends V> entry : entries) {
    write(entry.getKey(), entry.getValue());
  }
}