本文整理匯總了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,','));
});
}
示例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();
}
}
示例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);
}));
}
示例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));
}
});
}
示例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();
}
}
示例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;
}
}
示例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;
}
示例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()));
}
示例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());
}
示例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);
});
}
示例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());
});
}
示例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--");
}
示例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;
}
示例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;
}
示例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;
}