当前位置: 首页>>代码示例>>Java>>正文


Java Map.forEach方法代码示例

本文整理汇总了Java中java.util.Map.forEach方法的典型用法代码示例。如果您正苦于以下问题:Java Map.forEach方法的具体用法?Java Map.forEach怎么用?Java Map.forEach使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.util.Map的用法示例。


在下文中一共展示了Map.forEach方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: printReport

import java.util.Map; //导入方法依赖的package包/类
public void printReport(Class<?> springConfigurationClass) {
    System.err.println("Configuration layers:\n");
    getConfigurationLayers(springConfigurationClass).forEach((layer,classes) -> {
        System.err.println("" + layer + "\t" + StringUtils.join(classes,','));
    });

    System.err.println("\n\nDependencies:\n");
    Map<String, Set<String>> beanDependencies = getBeanDependencies();
    beanDependencies.forEach((name,dependencies) -> {
        System.err.println(name + ": " + StringUtils.join(dependencies,','));
    });
    System.err.println("\n\nReverse dependencies:\n");
    Map<String, Set<String>> reverseBeanDependencies = getReverseBeanDependencies();
    reverseBeanDependencies.forEach((name,dependencies) -> {
        System.err.println(name + ": " + StringUtils.join(dependencies,','));
    });

    System.err.println("\n\nBean dependency graph:\n");
    System.err.println(getBeanGraph());
    System.err.println("Bean layers:\n");

    getBeanGraph().getLayers().forEach((layer,classes) -> {
        System.err.println("" + layer + "\t" + StringUtils.join(classes,','));
    });
}
 
开发者ID:jillesvangurp,项目名称:spring-depend,代码行数:26,代码来源:SpringDependencyAnalyzer.java

示例2: executeJpqlQuery

import java.util.Map; //导入方法依赖的package包/类
/**
 * @return the number of entities updated or deleted
 */
public int executeJpqlQuery(@Nonnull final String queryString, @Nullable final Map<String, Object> parameters)
        throws DatabaseException {
    final EntityManager em = this.databaseConnection.getEntityManager();
    try {
        final Query query = em.createQuery(queryString);
        if (parameters != null) {
            parameters.forEach(query::setParameter);
        }
        em.getTransaction().begin();
        final int updatedOrDeleted = query.executeUpdate();
        em.getTransaction().commit();
        return updatedOrDeleted;
    } catch (final PersistenceException e) {
        final String message = String.format("Failed to execute JPQL query %s with %s parameters on DB %s",
                queryString, parameters != null ? parameters.size() : "null", this.databaseConnection.getName());
        throw new DatabaseException(message, e);
    } finally {
        em.close();
    }
}
 
开发者ID:napstr,项目名称:SqlSauce,代码行数:24,代码来源:DatabaseWrapper.java

示例3: assertForeignKeys

import java.util.Map; //导入方法依赖的package包/类
public static void assertForeignKeys(GraphDatabaseService neo4j, Neo4jVersionerCore neo4jVersionerCore, Map<Tuple2<String, String>, Map<String, String>> relationships) {

		ResourceIterator<Optional<Node>> tablesStateList = neo4j.findNodes(Label.label("Table")).map(table -> neo4jVersionerCore.findStateNode(table.getId()));

		List<Relationship> foreignKeysList = tablesStateList.stream()
				.map(tableStateOpt -> tableStateOpt.get().getRelationships(Direction.OUTGOING, RelationshipType.withName("RELATION")))
				.flatMap(list -> StreamSupport.stream(list.spliterator(), false))
				.collect(toList());

		assertThat(foreignKeysList)
				.hasSize(relationships.size());

		relationships.forEach((keys, description) -> assertThat(foreignKeysList).anySatisfy(foreignKey -> {
			assertThat(foreignKey.getStartNode().hasProperty(keys.a)).isTrue();
			assertThat(foreignKey.getEndNode().hasProperty(keys.b)).isTrue();
			assertThat(foreignKey.getAllProperties()).containsAllEntriesOf(description);
		}));
	}
 
开发者ID:h-omer,项目名称:neo4j-versioner-sql,代码行数:19,代码来源:TestData.java

示例4: test01

import java.util.Map; //导入方法依赖的package包/类
/**
 * Set-Cookie:xqat=93b9123bccf67168e3adb0c07d89b9e1f6cc8db6; domain=.xueqiu.com; path=/; expires=Mon, 23 May 2016 13:36:54 GMT; httpOnly
 Set-Cookie:xq_r_token=8cfa9fd958be66a0a6692ab80219e8eaecef6718; domain=.xueqiu.com; path=/; expires=Mon, 23 May 2016 13:36:54 GMT; httpOnly
 Set-Cookie:xq_is_login=1; domain=xueqiu.com; path=/; expires=Mon, 23 May 2016 13:36:54 GMT
 Set-Cookie:u=2970459786; domain=.xueqiu.com; path=/; expires=Mon, 23 May 2016 13:36:54 GMT; httpOnly
 Set-Cookie:xq_token_expire=Mon%20May%2023%202016%2021%3A36%3A54%20GMT%2B0800%20(CST); domain=.xueqiu.com; path=/; expires=Mon, 23 May 2016 13:36:54 GMT; httpOnly
 Set-Cookie:xq_a_token=93b9123bccf67168e3adb0c07d89b9e1f6cc8db6; domain=.xueqiu.com; path=/; expires=Mon, 23 May 2016 13:36:54 GMT; httpOnlyvv

 * @throws Exception
 */
@Test
public void test01() throws Exception {

    String base = "https://xueqiu.com/user/login";
    String param = "areacode=86&username=jt120lz%40gmail.com&password=3E0409E11A5756B971C54CC38035C198&remember_me=on";
    URL url = new URL(base+"?"+param);
    URLConnection conn = url.openConnection();
    conn.connect();
    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String s = null;
    while ((s = br.readLine()) != null) {
        System.out.println(s);
    }
    br.close();
    Map<String, List<String>> headers = conn.getHeaderFields();
    headers.forEach((key,value)-> {
        if (key.startsWith("Set-Cookie")) {
            value.forEach(v->System.out.println(v));
        }
    });
}
 
开发者ID:jt120,项目名称:take,代码行数:32,代码来源:LoginTest.java

示例5: selectJpqlQuerySingleResult

import java.util.Map; //导入方法依赖的package包/类
/**
 * Use this for COUNT() and similar jpql queries which are guaranteed to return a result
 */
@Nonnull
@CheckReturnValue
public <T> T selectJpqlQuerySingleResult(@Nonnull final String queryString,
                                         @Nullable final Map<String, Object> parameters,
                                         @Nonnull final Class<T> resultClass) throws DatabaseException {
    final EntityManager em = this.databaseConnection.getEntityManager();
    try {
        final Query q = em.createQuery(queryString);
        if (parameters != null) {
            parameters.forEach(q::setParameter);
        }
        em.getTransaction().begin();
        final T result = resultClass.cast(q.getSingleResult());
        em.getTransaction().commit();
        return setSauce(result);
    } catch (final PersistenceException | ClassCastException e) {
        final String message = String.format("Failed to select single result JPQL query %s with %s parameters for class %s on DB %s",
                queryString, parameters != null ? parameters.size() : "null", resultClass.getName(), this.databaseConnection.getName());
        throw new DatabaseException(message, e);
    } finally {
        em.close();
    }
}
 
开发者ID:napstr,项目名称:SqlSauce,代码行数:27,代码来源:DatabaseWrapper.java

示例6: findTestResources

import java.util.Map; //导入方法依赖的package包/类
/**
 * Finds {@link IFile} and containing {@link IProject} for xpect file that is currently processed.
 *
 * Looks through all available projects and finds all files that match (by {@link URI}) to currently processed xpect
 * file. If only one file in only one project is found, returns that mapping, throws error in other cases
 *
 * @return {@link java.util.Map.Entry} map entry of file and containing project for a given
 *         {@link org.eclipse.xpect.XpectFile}
 */
private Entry<IFile, IProject> findTestResources() throws RuntimeException {
	Map<IFile, IProject> files2projects = new HashMap<>();

	IProject[] worksapceProjects = ResourcesPlugin.getWorkspace().getRoot().getProjects();

	String xtFileLocation = ctx.getXpectFileURI().toString();// file://C:/Users/Administrator/runtime-New_configuration/yyyyyyyyyyyyyyyyyy/src/TestFile_001.n4js.xt

	for (IProject iProject : worksapceProjects) {
		String projLoc = iProject.getLocationURI().toString();
		if (xtFileLocation.startsWith(projLoc)) {
			String lkp = xtFileLocation.substring(projLoc.length());// file:/C:/Users/Administrator/runtime-New_configuration/yyyyyyyyyyyyyyyyyy
			IFile lkpFile = (IFile) iProject.findMember(lkp);
			if (lkpFile != null) {
				files2projects.put(lkpFile, iProject);
			}
		}
	}

	RuntimeException re = null;
	switch (files2projects.size()) {
	case 0:
		re = new RuntimeException("cannot find any file and project for processed xpect file");
		N4IDEXpectUIPlugin.logError("no projects with files mathching " + xtFileLocation + " found", re);
		throw re;
	case 1:
		return files2projects.entrySet().iterator().next();

	default:
		re = new RuntimeException("cannot find single file and project for processed xpect file");
		StringBuilder sb = new StringBuilder("multiple projects matching " + xtFileLocation + " found");
		files2projects.forEach((file, project) -> {
			sb.append("\n file : " + file.getRawLocation().toString() + ", project :: "
					+ project.getRawLocation().toString());
		});
		N4IDEXpectUIPlugin.logError(sb.toString(), re);
		throw re;
	}
}
 
开发者ID:eclipse,项目名称:n4js,代码行数:48,代码来源:N4IDEXpectFileSetup.java

示例7: parseResponseForAllPaths

import java.util.Map; //导入方法依赖的package包/类
public HashMap<String, SwaggerResponseSchema> parseResponseForAllPaths() {
    Map<String, Path> paths = swagger.getPaths();
    HashMap<String, SwaggerResponseSchema> responses = new HashMap<>();
    paths.forEach((path, methods) -> {
        Map<HttpMethod, Operation> operationMap = methods.getOperationMap();
        operationMap.forEach(((httpMethod, operation) -> {
            SwaggerResponseSchema response = parseReponseForGivenPathHTTPMethodAndAllResponseType(path, httpMethod);
            responses.put(httpMethod.name() + path, response);
        }));
    });
    return responses;
}
 
开发者ID:bsneha90,项目名称:RecursiveSwaggerSchemaParser,代码行数:13,代码来源:SwaggerSchemaResponseParser.java

示例8: initNodeServerDiscovery

import java.util.Map; //导入方法依赖的package包/类
/**
 * 初始化node-server列表
 */
private void initNodeServerDiscovery() {
    nodeServerPool.clear();
    Map<String, String> datas = zkUtils.readTargetChildsData(ZkGroupEnum.NODE_SERVER.getValue());
    if (datas != null) {
        datas.forEach((k, v) -> nodeServerPool.put(k, JSON.parseObject(v, NodeServerInfo.class)));
    }
    nodeServerPool().forEach((k, v) -> nodeManager.put(k, v.getIntranetIp(), v.getNodePort(), v.getInternetIp(), v.getDevicePort()));

}
 
开发者ID:lee123lee123,项目名称:GoPush,代码行数:13,代码来源:NodeServerDiscoveryService.java

示例9: testDelay

import java.util.Map; //导入方法依赖的package包/类
@Test
public void testDelay() throws Exception {
    int failoverDelay = 200;

    failures.set(channels.size() * 3);

    Map<ClusterNodeId, List<Long>> times = new HashMap<>();

    channels.forEach(c -> times.put(c.getNodeId(), Collections.synchronizedList(new ArrayList<>())));

    AggregateResult<String> result = get(sender.get().withFailover(ctx -> {
        times.get(ctx.failedNode().id()).add(currentTimeMillis());

        return ctx.retry().withDelay(failoverDelay);
    }).aggregate("test"));

    times.forEach((id, series) -> {
        assertEquals(3, series.size());

        long prevTime = 0;

        for (Long time : series) {
            if (prevTime == 0) {
                prevTime = time;
            } else {
                assertTrue(time - prevTime >= failoverDelay);

                prevTime = time;
            }
        }
    });

    assertTrue(result.isSuccess());
    assertEquals(channels.size(), result.results().size());
}
 
开发者ID:hekate-io,项目名称:hekate,代码行数:36,代码来源:FailoverAggregateTest.java

示例10: appendAdditionalCookies

import java.util.Map; //导入方法依赖的package包/类
private void appendAdditionalCookies(CookieStore store, Map<String, String> cookies, String domain, String path, Date expiryDate) {
    cookies.forEach((key, value) -> {
        BasicClientCookie cookie = new BasicClientCookie(key, value);
        cookie.setDomain(domain);
        cookie.setPath(path);
        cookie.setExpiryDate(expiryDate);
        store.addCookie(cookie);
    });
}
 
开发者ID:kanjielu,项目名称:jeeves,代码行数:10,代码来源:WechatHttpServiceInternal.java

示例11: handleProfileCommand

import java.util.Map; //导入方法依赖的package包/类
private void handleProfileCommand() {
	if (!Cloud.getInstance().getProfiler().isEnabled()) {
		Cloud.getLogger().info("Profiler is not enabled!");
		return;
	}
	Map<String, List<CentauriProfiler.Profile>> keyToProfiles = new HashMap<>();

	Cloud.getInstance().getProfiler().getProfiles().forEach(profile -> {
		if (!keyToProfiles.containsKey(profile.getKey()))
			keyToProfiles.put(profile.getKey(), new ArrayList<>());
		keyToProfiles.get(profile.getKey()).add(profile);
	});

	keyToProfiles.forEach((key, profiles) -> {
		final ProfilerStatistic statistic = new ProfilerStatistic();

		profiles.forEach(profile -> {
			if (profile.getTime() < statistic.getMin())
				statistic.setMin(profile.getTime());

			if (profile.getTime() > statistic.getMax())
				statistic.setMax(profile.getTime());

			statistic.setAvg(statistic.getAvg() + profile.getTime());
		});

		statistic.setAvg(statistic.getAvg() / profiles.size());

		Cloud.getLogger().info("Key: {}, Min: {}ms, Max: {}ms, Avg: {}ms", key, statistic.getMin(), statistic.getMax(), statistic.getAvg());
	});
}
 
开发者ID:CentauriCloud,项目名称:CentauriCloud,代码行数:32,代码来源:CentauriCloudCommandListener.java

示例12: printElasticSearchInfo

import java.util.Map; //导入方法依赖的package包/类
private void printElasticSearchInfo() {

        System.out.println("--ElasticSearch-->");
        Client client = es.getClient();
        Map<String, String> asMap = client.settings().getAsMap();

        asMap.forEach((k, v) -> {
            System.out.println(k + " = " + v);
        });
        System.out.println("<--ElasticSearch--");
    }
 
开发者ID:chanakaDe,项目名称:ensembl-elastic-rest-final,代码行数:12,代码来源:Application.java

示例13: apply

import java.util.Map; //导入方法依赖的package包/类
@Override
protected Map<String, PropertyValue> apply(Map<String, PropertyValue> input) {
	final Map<String, PropertyValue> output = new HashMap<>();
	input.forEach((key, value) -> {
		output.put(key.toLowerCase().replace("_", "."), value);
	});
	return output;
}
 
开发者ID:ufoscout,项目名称:properlty,代码行数:9,代码来源:ToLowerCaseAndDotKeyReader.java

示例14: generateTestJar

import java.util.Map; //导入方法依赖的package包/类
public static Path generateTestJar(Pair<String, byte[]>... files) {
    Path jarFile;
    try {
        jarFile = Files.createTempFile("testjar", ".jar");
        try(ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(jarFile))) {
            Map<String, List<Pair<String, byte[]>>> filesMap = new HashMap<>();
            for (Pair<String, byte[]> file : files) {
                filesMap.compute(file.getKey(), (k, data) -> {
                    List<Pair<String, byte[]>> fileData = data != null ? data : new ArrayList<>();
                    fileData.add(new Pair<>(file.getKey(), compress(file.getValue())));
                    return fileData;
                });
            }

            filesMap.forEach((path, data) -> {
                putPath(Paths.get(path).getParent().toString(), zos);
                data.forEach(file -> putFile(file.getKey(), file.getValue(), zos));
            });

            zos.closeEntry();
            zos.finish();
        }
    } catch (Throwable e) {
        SneakyThrow.throwException(e);
        return null;
    }
    //jarFile.toFile().deleteOnExit();
    return jarFile;
}
 
开发者ID:mikroskeem,项目名称:Shuriken,代码行数:30,代码来源:Utils.java

示例15: offset

import java.util.Map; //导入方法依赖的package包/类
public static Map<String, List<OffsetStat>> offset(String group, String topic, String start, String end) {
  Map<String, List<OffsetStat>> statsMap = new HashMap<String, List<OffsetStat>>();
  String indexPrefix = SystemManager.getConfig().getEsIndex();
  try {
    ElasticsearchAssistEntity assistEntity = ScrollSearchTemplate.getInterval(start, end);

    List<String> indexes = new ArrayList<String>();
    assistEntity.getIndexs().forEach(a -> {
      indexes.add(indexPrefix + "-" + a);
    });

    String[] esHost = SystemManager.getConfig().getEsHosts().split("[,;]")[0].split(":");

    String url = "http://" + esHost[0] + ":" + esHost[1] + "/" + String.join(",", indexes) + "/"
        + SystemManager.getElasticSearchOffsetType() + "/_search?ignore_unavailable=true&allow_no_indices=true";

    ResponseEntity<String> response = REST.exchange(url, HttpMethod.POST,
        new HttpEntity<String>(ScrollSearchTemplate.getOffset(group, topic, assistEntity), headers), String.class);
    String searchResult = response.getBody();
    JSONObject temp = new JSONObject(searchResult);
    JSONArray temp2 = temp.getJSONObject("aggregations").getJSONObject("aggs").getJSONArray("buckets");
    List<OffsetStat> stats = new ArrayList<OffsetStat>();
    temp2.forEach(obj -> {
      JSONObject item = (JSONObject) obj;
      JSONArray xx = item.getJSONObject("group").getJSONArray("buckets");
      for (int i = 0; i < xx.length(); i++) {
        JSONObject item2 = xx.getJSONObject(i);
        JSONArray xxx = item2.getJSONObject("topic").getJSONArray("buckets");
        for (int j = 0; j < xxx.length(); j++) {
          JSONObject item3 = xxx.getJSONObject(j);
          stats.add(new OffsetStat(item.getLong("key"), item2.get("key").toString(), item3.get("key").toString(),
              item3.getJSONObject("offset").getLong("value"), item3.getJSONObject("lag").getLong("value")));
        }
      }
    });

    stats.forEach(a -> {
      String topicName = a.getTopic();
      if (topicName == null || topicName.length() == 0) {
        topicName = "empty";
      }
      if (statsMap.containsKey(topicName)) {
        statsMap.get(topicName).add(a);
      } else {
        List<OffsetStat> arr = new ArrayList<OffsetStat>();
        arr.add(a);
        statsMap.put(topicName, arr);
      }
    });

    statsMap.forEach((key, val) -> {
      for (int i = val.size() - 1; i > 0; i--) {
        val.get(i).setOffset(val.get(i).getOffset() - val.get(i - 1).getOffset());
      }
      val.remove(0);
    });

  } catch (Exception e) {
    // TODO
    LOG.error("Damn...", e);
  }
  return statsMap;
}
 
开发者ID:chickling,项目名称:kmanager,代码行数:64,代码来源:ElasticsearchRESTUtil.java


注:本文中的java.util.Map.forEach方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。