Java Code Examples for java.util.Map.entrySet()

The following are Jave code examples for showing how to use entrySet() of the java.util.Map class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: guava-mock   File: MapInterfaceTest.java   View Source Code Vote up 6 votes
public void testEntrySetSetValue() {
  // TODO: Investigate the extent to which, in practice, maps that support
  // put() also support Entry.setValue().
  if (!supportsPut) {
    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 2
Project: dataplatform-schema-lib   File: TextMapFormatter.java   View Source Code Vote up 6 votes
public void write(final ByteArrayData buffer , final Object obj ) throws IOException{
  if( ! ( obj instanceof Map ) ){
    return;
  }
  Map<Object,Object> mapObj = (Map<Object,Object>)obj;
  int i = 0;
  for( Map.Entry<Object,Object> entry : mapObj.entrySet() ){
    String key = entry.getKey().toString();
    ITextFormatter childFormatter = childFormatterContainer.get( key );
    if( childFormatter == null ){
      childFormatter = defaultFormatter;
    }
    if( i != 0 ){
      buffer.append( delimiter );
    }
    buffer.append( key.getBytes( "UTF-8" ) );
    buffer.append( fieldDelimiter );
    childFormatter.write( buffer , entry.getValue() );

    i++;
  }
}
 
Example 3
Project: Recognize-it   File: MediaReader.java   View Source Code Vote up 6 votes
/**
 * Scan the list of pictures in the library.
 */
@WorkerThread
public ArrayList<AlbumFolder> getAllImage() {
    Map<String, AlbumFolder> albumFolderMap = new HashMap<>();
    AlbumFolder allFileFolder = new AlbumFolder();
    allFileFolder.setChecked(true);
    allFileFolder.setName(mContext.getString(R.string.album_all_images));

    scanImageFile(albumFolderMap, allFileFolder);

    ArrayList<AlbumFolder> albumFolders = new ArrayList<>();
    Collections.sort(allFileFolder.getAlbumFiles());
    albumFolders.add(allFileFolder);

    for (Map.Entry<String, AlbumFolder> folderEntry : albumFolderMap.entrySet()) {
        AlbumFolder albumFolder = folderEntry.getValue();
        Collections.sort(albumFolder.getAlbumFiles());
        albumFolders.add(albumFolder);
    }
    return albumFolders;
}
 
Example 4
Project: apache-tomcat-7.0.73-with-comment   File: TestResponse.java   View Source Code Vote up 5 votes
@Test
public void testBug49598() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    Tomcat.addServlet(ctx, "servlet", new Bug49598Servlet());
    ctx.addServletMapping("/", "servlet");

    tomcat.start();

    Map<String,List<String>> headers = new HashMap<String,List<String>>();
    getUrl("http://localhost:" + getPort() + "/", new ByteChunk(), headers);

    // Check for headers without a name
    for (Map.Entry<String,List<String>> header : headers.entrySet()) {
        if (header.getKey() == null) {
            // Expected if this is the response line
            List<String> values = header.getValue();
            if (values.size() == 1 &&
                    values.get(0).startsWith("HTTP/1.1")) {
                continue;
            }
            fail("Null header name detected for value " + values);
        }
    }

    // Check for exactly one Set-Cookie header
    int count = 0;
    for (String headerName : headers.keySet()) {
        if ("Set-Cookie".equals(headerName)) {
            count ++;
        }
    }
    assertEquals(1, count);
}
 
Example 5
Project: updatebot   File: PomHelper.java   View Source Code Vote up 5 votes
public static boolean updateProperties(Document doc, Map<String, String> propertyChanges) {
    Element rootElement = doc.getRootElement();
    boolean update = false;
    Element properties = DecentXmlHelper.firstChild(rootElement, "properties");
    if (properties != null) {
        for (Map.Entry<String, String> entry : propertyChanges.entrySet()) {
            String propertyName = entry.getKey();
            String propertyVersion = entry.getValue();
            if (DecentXmlHelper.updateFirstChild(properties, propertyName, propertyVersion)) {
                update = true;
            }
        }
    }
    return update;
}
 
Example 6
Project: ZentrelaCore   File: TextualComponent.java   View Source Code Vote up 5 votes
public static ComplexTextTypeComponent deserialize(Map<String, Object> map) {
    String key = null;
    Map<String, String> value = new HashMap<String, String>();
    for (Map.Entry<String, Object> valEntry : map.entrySet()) {
        if (valEntry.getKey().equals("key")) {
            key = (String) valEntry.getValue();
        } else if (valEntry.getKey().startsWith("value.")) {
            value.put(((String) valEntry.getKey()).substring(6) /* Strips out the value prefix */, valEntry.getValue().toString());
        }
    }
    return new ComplexTextTypeComponent(key, value);
}
 
Example 7
Project: incubator-netbeans   File: RepositoryInfo.java   View Source Code Vote up 5 votes
private static boolean equalsBranches (Map<String, GitBranch> oldBranches, Map<String, GitBranch> newBranches) {
    boolean retval = oldBranches.size() == newBranches.size() && oldBranches.keySet().equals(newBranches.keySet());
    if (retval) {
        for (Map.Entry<String, GitBranch> e : oldBranches.entrySet()) {
            GitBranch oldBranch = e.getValue();
            GitBranch newBranch = newBranches.get(e.getKey());
            if (!oldBranch.getId().equals(newBranch.getId())
                    || !equalTracking(newBranch, oldBranch)) {
                retval = false;
                break;
            }
        }
    }
    return retval;
}
 
Example 8
Project: springboot-shiro-cas-mybatis   File: ServiceThemeResolver.java   View Source Code Vote up 5 votes
/**
 * Sets the map of mobile browsers.  This sets a flag on the request called "isMobile" and also
 * provides the custom flag called browserType which can be mapped into the theme.
 * <p>
 * Themes that understand isMobile should provide an alternative stylesheet.
 *
 * @param mobileOverrides the list of mobile browsers.
 */
public void setMobileBrowsers(final Map<String, String> mobileOverrides) {
    // initialize the overrides variable to an empty map
    this.overrides = new HashMap<>();

    for (final Map.Entry<String, String> entry : mobileOverrides.entrySet()) {
        this.overrides.put(Pattern.compile(entry.getKey()), entry.getValue());
    }
}
 
Example 9
Project: hadoop   File: MetricsServlet.java   View Source Code Vote up 5 votes
/**
 * Prints metrics data in a multi-line text form.
 */
void printMap(PrintWriter out, Map<String, Map<String, List<TagsMetricsPair>>> map) {
  for (Map.Entry<String, Map<String, List<TagsMetricsPair>>> context : map.entrySet()) {
    out.print(context.getKey());
    out.print("\n");
    for (Map.Entry<String, List<TagsMetricsPair>> record : context.getValue().entrySet()) {
      indent(out, 1);
      out.print(record.getKey());
      out.print("\n");
      for (TagsMetricsPair pair : record.getValue()) {
        indent(out, 2);
        // Prints tag values in the form "{key=value,key=value}:"
        out.print("{");
        boolean first = true;
        for (Map.Entry<String, Object> tagValue : pair.tagMap.entrySet()) {
          if (first) {
            first = false;
          } else {
            out.print(",");
          }
          out.print(tagValue.getKey());
          out.print("=");
          out.print(tagValue.getValue().toString());
        }
        out.print("}:\n");
        
        // Now print metric values, one per line
        for (Map.Entry<String, Number> metricValue : 
            pair.metricMap.entrySet()) {
          indent(out, 3);
          out.print(metricValue.getKey());
          out.print("=");
          out.print(metricValue.getValue().toString());
          out.print("\n");
        }
      }
    }
  }    
}
 
Example 10
Project: EatDubbo   File: UrlUtils.java   View Source Code Vote up 5 votes
public static Map<String, Map<String, String>> revertNotify(Map<String, Map<String, String>> notify) {
    if (notify != null && notify.size() > 0) {
        Map<String, Map<String, String>> newNotify = new HashMap<String, Map<String, String>>();
        for (Map.Entry<String, Map<String, String>> entry : notify.entrySet()) {
            String serviceName = entry.getKey();
            Map<String, String> serviceUrls = entry.getValue();
            if (!serviceName.contains(":") && !serviceName.contains("/")) {
                if (serviceUrls != null && serviceUrls.size() > 0) {
                    for (Map.Entry<String, String> entry2 : serviceUrls.entrySet()) {
                        String url = entry2.getKey();
                        String query = entry2.getValue();
                        Map<String, String> params = StringUtils.parseQueryString(query);
                        String group = params.get("group");
                        String version = params.get("version");
                        // params.remove("group");
                        // params.remove("version");
                        String name = serviceName;
                        if (group != null && group.length() > 0) {
                            name = group + "/" + name;
                        }
                        if (version != null && version.length() > 0) {
                            name = name + ":" + version;
                        }
                        Map<String, String> newUrls = newNotify.get(name);
                        if (newUrls == null) {
                            newUrls = new HashMap<String, String>();
                            newNotify.put(name, newUrls);
                        }
                        newUrls.put(url, StringUtils.toQueryString(params));
                    }
                }
            } else {
                newNotify.put(serviceName, serviceUrls);
            }
        }
        return newNotify;
    }
    return notify;
}
 
Example 11
Project: dremio-oss   File: Distribution.java   View Source Code Vote up 5 votes
public Distribution(String name, Map<String, Integer> distribution)
{
    this.name = checkNotNull(name, "name is null");
    checkNotNull(distribution, "distribution is null");

    ImmutableList.Builder<String> values = ImmutableList.builder();
    this.weights = new int[distribution.size()];

    int runningWeight = 0;
    int index = 0;
    boolean isValidDistribution = true;
    for (Entry<String, Integer> entry : distribution.entrySet()) {
        values.add(entry.getKey());

        runningWeight += entry.getValue();
        weights[index] = runningWeight;

        isValidDistribution = isValidDistribution && entry.getValue() > 0;

        index++;
    }
    this.values = values.build();

    // "nations" is hack and not a valid distribution so we need to skip it
    if (isValidDistribution) {
        this.maxWeight = weights[weights.length - 1];
        this.distribution = new String[maxWeight];

        index = 0;
        for (String value : this.values) {
            int count = distribution.get(value);
            for (int i = 0; i < count; i++) {
                this.distribution[index++] = value;
            }
        }
    } else {
        this.maxWeight = -1;
        this.distribution = null;
    }
}
 
Example 12
Project: dubbox-hystrix   File: RedisRegistry.java   View Source Code Vote up 5 votes
private void clean(Jedis jedis) {
    Set<String> keys = jedis.keys(root + Constants.ANY_VALUE);
    if (keys != null && keys.size() > 0) {
        for (String key : keys) {
            Map<String, String> values = jedis.hgetAll(key);
            if (values != null && values.size() > 0) {
                boolean delete = false;
                long now = System.currentTimeMillis();
                for (Map.Entry<String, String> entry : values.entrySet()) {
                    URL url = URL.valueOf(entry.getKey());
                    if (url.getParameter(Constants.DYNAMIC_KEY, true)) {
                        long expire = Long.parseLong(entry.getValue());
                        if (expire < now) {
                            jedis.hdel(key, entry.getKey());
                            delete = true;
                            if (logger.isWarnEnabled()) {
                                logger.warn("Delete expired key: " + key + " -> value: " + entry.getKey() + ", expire: " + new Date(expire) + ", now: " + new Date(now));
                            }
                        }
                    }
                }
                if (delete) {
                    jedis.publish(key, Constants.UNREGISTER);
                }
            }
        }
    }
}
 
Example 13
Project: android-apkbox   File: ApkNative.java   View Source Code Vote up 5 votes
/**
 * unzipLibFiles
 *
 * @param zipFile  zipFile
 * @param abis     abis
 * @param libFiles libFiles
 */
private final static void unzipLibFiles(String zipFile, String[] abis, Map<String, Map<String, String>> libFiles) {
    for (int i = 0; i < abis.length; i++) {
        Map<String, String> files = libFiles.get(abis[i]);
        if (files != null && !files.isEmpty()) {
            for (Map.Entry<String, String> entry : files.entrySet()) {
                unzipSingleFile(zipFile, entry.getKey(), entry.getValue());
            }
        }
    }
}
 
Example 14
Project: Review-   File: FavListFragment.java   View Source Code Vote up 5 votes
@Override
protected Void doInBackground(Void... params) {
    SharedPreferences sp = CacheHelper.getPreferences(CacheHelper.FAV);
    Map<String, ?> map = sp.getAll();
    for (Map.Entry<String, ?> entry : map.entrySet()) {
        if (entry.getValue() instanceof Integer) {
            Integer testId = (Integer) entry.getValue();
            mData.add(readTestCache(testId));
        }
    }
    return null;
}
 
Example 15
Project: yacy_grid_mcp   File: ComparableARC.java   View Source Code Vote up 4 votes
@Override
public void putAll(Map<? extends K, ? extends V> map) {
    for (Map.Entry<? extends K, ? extends V> entry: map.entrySet()) put(entry.getKey(), entry.getValue());
}
 
Example 16
Project: lams   File: QualifierAnnotationAutowireCandidateResolver.java   View Source Code Vote up 4 votes
/**
 * Match the given qualifier annotation against the candidate bean definition.
 */
protected boolean checkQualifier(
		BeanDefinitionHolder bdHolder, Annotation annotation, TypeConverter typeConverter) {

	Class<? extends Annotation> type = annotation.annotationType();
	RootBeanDefinition bd = (RootBeanDefinition) bdHolder.getBeanDefinition();

	AutowireCandidateQualifier qualifier = bd.getQualifier(type.getName());
	if (qualifier == null) {
		qualifier = bd.getQualifier(ClassUtils.getShortName(type));
	}
	if (qualifier == null) {
		// First, check annotation on factory method, if applicable
		Annotation targetAnnotation = getFactoryMethodAnnotation(bd, type);
		if (targetAnnotation == null) {
			RootBeanDefinition dbd = getResolvedDecoratedDefinition(bd);
			if (dbd != null) {
				targetAnnotation = getFactoryMethodAnnotation(dbd, type);
			}
		}
		if (targetAnnotation == null) {
			// Look for matching annotation on the target class
			if (getBeanFactory() != null) {
				Class<?> beanType = getBeanFactory().getType(bdHolder.getBeanName());
				if (beanType != null) {
					targetAnnotation = AnnotationUtils.getAnnotation(ClassUtils.getUserClass(beanType), type);
				}
			}
			if (targetAnnotation == null && bd.hasBeanClass()) {
				targetAnnotation = AnnotationUtils.getAnnotation(ClassUtils.getUserClass(bd.getBeanClass()), type);
			}
		}
		if (targetAnnotation != null && targetAnnotation.equals(annotation)) {
			return true;
		}
	}

	Map<String, Object> attributes = AnnotationUtils.getAnnotationAttributes(annotation);
	if (attributes.isEmpty() && qualifier == null) {
		// If no attributes, the qualifier must be present
		return false;
	}
	for (Map.Entry<String, Object> entry : attributes.entrySet()) {
		String attributeName = entry.getKey();
		Object expectedValue = entry.getValue();
		Object actualValue = null;
		// Check qualifier first
		if (qualifier != null) {
			actualValue = qualifier.getAttribute(attributeName);
		}
		if (actualValue == null) {
			// Fall back on bean definition attribute
			actualValue = bd.getAttribute(attributeName);
		}
		if (actualValue == null && attributeName.equals(AutowireCandidateQualifier.VALUE_KEY) &&
				expectedValue instanceof String && bdHolder.matchesName((String) expectedValue)) {
			// Fall back on bean name (or alias) match
			continue;
		}
		if (actualValue == null && qualifier != null) {
			// Fall back on default, but only if the qualifier is present
			actualValue = AnnotationUtils.getDefaultValue(annotation, attributeName);
		}
		if (actualValue != null) {
			actualValue = typeConverter.convertIfNecessary(actualValue, expectedValue.getClass());
		}
		if (!expectedValue.equals(actualValue)) {
			return false;
		}
	}
	return true;
}
 
Example 17
Project: JLink   File: MaxRecall.java   View Source Code Vote up 4 votes
public static void main(String[] args) throws IOException, ParseException {

		Parameter parameter;

		if (args == null || args.length == 0) {
			parameter = ParameterReader.defaultParameters();
		} else {
			parameter = ParameterReader.readParametersFromCommandLine(args);
		}
		new JLink(Main.buildSettings(parameter));
		dict = CollectiveDictionaryFactory.getInstance();
		int j = 0;
		double i = 0;
		for (String string : dict.getAllSurfaceForms()) {
			i += dict.getConceptsForNormalizedSurfaceForm(string).size();
			if (dict.getConceptsForNormalizedSurfaceForm(string).size() != 1) {
				System.out.println(string);
				System.out.println(dict.getConceptsForNormalizedSurfaceForm(string));
				j++;
			}
		}
		System.out.println(dict.getAllSurfaceForms().size() / i);
		System.out.println("j = " + j);
		System.out.println(dict.getAllSurfaceForms().size());
		System.exit(1);
		luceneRetrieval = LuceneRetrieval.getInstance();

		// System.out.println(
		// luceneRetrieval.getFuzzyCandidates("methamphetamine",
		// LUCENE_MAX_RESULTS, LUCENE_SIMILARITY_TRESHOLD));
		//
		// System.exit(1);

		// NgramRetrieval = JaccardRetrieval.getInstance();
		// levenshteinRetrieval = LevenshteinRetrieval.getInstance();

		// String set = "testset";

		EDataset set = EDataset.TEST;

		Map<String, Set<String>> goldData = DataReader.loadChemicalAnnotationData(set, true, true);

		Map<String, Set<String>> annotations = DataReader.loadChemicalAnnotationData(set, false, false);

		if (JLink.type == EType.Chemical) {

			goldData = DataReader.loadChemicalAnnotationData(set, true, true);

			annotations = DataReader.loadChemicalAnnotationData(set, false, false);
		} else if (JLink.type == EType.Disease) {

			goldData = DataReader.loadDiseaseAnnotationData(set, true, true);

			annotations = DataReader.loadDiseaseAnnotationData(set, false, false);

		}

		// Map<String, Set<String>> resultIDF =
		// calculateResultIDF(annotations);

		Map<String, Set<Concept>> results = getIDs(annotations);

		Map<String, Set<String>> simpleResult = new HashMap<>();

		for (Entry<String, Set<Concept>> resultEntry : results.entrySet()) {

			simpleResult.putIfAbsent(resultEntry.getKey(), new HashSet<>());
			simpleResult.get(resultEntry.getKey())
					.addAll(resultEntry.getValue().stream().map(c -> c.conceptID).collect(Collectors.toList()));
		}

		PRF1Extended.calculate(goldData, simpleResult);

		analyze(goldData, simpleResult);

	}
 
Example 18
Project: Hydrograph   File: SubJobPortLinkUtilty.java   View Source Code Vote up 4 votes
/**
 * Adds the output sub graph component and link.
 *
 * @param container the container
 * @param cacheInputSubjobComp the cache input subjob comp
 * @param cacheOutSubjobComp the cache out subjob comp
 * @param clipboardList the clipboard list
 * @return the component
 */
public static Component addOutputSubJobComponentAndLink(Container container,Map<Component,Integer> cacheInputSubjobComp,Map<Component,List<String>> cacheOutSubjobComp,List clipboardList){
	 int inPort=0;
	OutputSubjobComponent outSubComponent=new OutputSubjobComponent();
	Map<String, ComponentsOutputSchema> schemaMap = new HashMap<String, ComponentsOutputSchema>();
	for (Map.Entry<Component,List<String>> entry : cacheOutSubjobComp.entrySet()) {
	   					outSubComponent.setProperties(new LinkedHashMap<String,Object>());
	   					for (String sourceTerminal : entry.getValue()) {
	   					Link linkNew = new Link();
						linkNew.setSource(entry.getKey());
						linkNew.setTarget(outSubComponent);
						linkNew.setSourceTerminal(sourceTerminal);
						linkNew.setTargetTerminal(Constants.INPUT_SOCKET_TYPE+inPort);
						entry.getKey().connectOutput(linkNew);
						outSubComponent.connectInput(linkNew);
						if(entry.getKey() instanceof CloneComponent){
							rearrangeLinkNumbers(entry.getKey());
						}
						outSubComponent.getProperties().put(Constants.TYPE, Constants.OUTPUT_SUBJOB);			
						inPort++;
	   					}		   					
						if(cacheInputSubjobComp.get(entry.getKey())==null){
							container.addSubJobChild(entry.getKey());
							clipboardList.remove(entry.getKey());
						}							

	   	}
	   	if(cacheOutSubjobComp.size()>0){
	   		outSubComponent.getProperties().put(Constants.NAME,Constants.OUTPUT_SUBJOB);
	   		outSubComponent.setComponentLabel(Constants.OUTPUT_SUBJOB);
	   		outSubComponent.setComponentId(Constants.OUTPUT_SUBJOB);
	   		outSubComponent.setType(Constants.OUTPUT_SUBJOB_TYPE);
	   		outSubComponent.setCategory(Constants.SUBJOB_COMPONENT_CATEGORY);
	   		outSubComponent.completeInputPortSettings(inPort);	
	   		fixComponentSize(outSubComponent, inPort);
	   		setXYCoordinate(outSubComponent,getMaxXCoordinate(container)+300 , 0);
	   		outSubComponent.getProperties().put(Constants.SCHEMA_TO_PROPAGATE,schemaMap);
	   		outSubComponent.setParent(container); 
	   		container.addSubJobChild(outSubComponent);
	   		
	   	}
	   	return outSubComponent;
	}
 
Example 19
Project: dubbox-hystrix   File: JSONObject.java   View Source Code Vote up 4 votes
/**
 * put all.
 * 
 * @param map map.
 */
public void putAll(Map<String, Object> map)
{
	for( Map.Entry<String, Object> entry : map.entrySet() )
		mMap.put(entry.getKey(), entry.getValue());
}
 
Example 20
Project: Abacus-Lightweight-Stream-API   File: Stream.java   View Source Code Vote up 3 votes
/**
 * Creates a {@code Stream} from {@code Map} entries.
 *
 * @param <K> the type of map keys
 * @param <V> the type of map values
 * @param map  the map with elements to be passed to stream
 * @return the new stream
 * @throws NullPointerException if {@code map} is null
 */
public static <K, V> Stream<Map.Entry<K, V>> of(Map<K, V> map) {
    if (map == null || map.size() == 0) {
        return Stream.<Map.Entry<K, V>> empty();
    }

    return new Stream<>(map.entrySet());
}