本文整理匯總了Java中java.util.HashMap.forEach方法的典型用法代碼示例。如果您正苦於以下問題:Java HashMap.forEach方法的具體用法?Java HashMap.forEach怎麽用?Java HashMap.forEach使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類java.util.HashMap
的用法示例。
在下文中一共展示了HashMap.forEach方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: writeXMLFile
import java.util.HashMap; //導入方法依賴的package包/類
public void writeXMLFile(HashMap<String,String> lines,String path) throws IOException, XMLStreamException{
XMLOutputFactory xof = XMLOutputFactory.newInstance();
final XMLStreamWriter xtw = xof.createXMLStreamWriter(new FileWriter(path));
xtw.writeStartDocument("utf-8","1.0");
xtw.writeCharacters("\n");
lines.forEach((key,value) ->{
try {
xtw.writeStartElement(key);
xtw.writeCharacters(value);
xtw.writeEndElement();
xtw.writeCharacters("\n");
} catch (XMLStreamException ex) {
Logger.getLogger(XMLController.class.getName()).log(Level.SEVERE, null, ex);
}
});
xtw.writeEndDocument();
xtw.flush();
xtw.close();
}
示例2: cookiesToString
import java.util.HashMap; //導入方法依賴的package包/類
public static final String cookiesToString(HashMap<String, String> cookies) {
if (cookies == null) {
return null;
}
if (cookies.isEmpty()) {
return "";
}
try {
final StringBuilder out = new StringBuilder();
cookies.forEach((name, value) -> {
out.append(name);
out.append("=");
out.append(value);
out.append(";");
});
return out.substring(0, out.length() - ";".length());
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
示例3: moveAndRenameImageFiles
import java.util.HashMap; //導入方法依賴的package包/類
private void moveAndRenameImageFiles() throws AnkiExpectedExportingException {
HashMap<String, String> imageNamesDictionary = parser.getImageNamesDictionary();
File imagesFolder = new File(destinationFolder, "anki-images");
//noinspection ResultOfMethodCallIgnored
imagesFolder.mkdirs();
imageNamesDictionary.forEach((currentName, targetName) -> {
File originalFile = new File(parser.getUnzippedToFolder(), currentName);
File destinationFile = new File(imagesFolder, targetName);
try {
Files.copy(originalFile, destinationFile);
} catch (IOException e) {
throw new AnkiExpectedExportingException("Cannot move "+originalFile+" to "+destinationFile);
}
});
}
示例4: run
import java.util.HashMap; //導入方法依賴的package包/類
@Override
public void run() {
try {
final HashMap<UUID, Integer> counts = Maps.newHashMap();
gifts.forEach(playerId -> counts.merge(playerId, 1, Integer::sum));
counts.forEach((playerId, count) -> onlinePlayers.byUuid(playerId).ifPresent(player -> {
RaindropUtil.giveRaindrops(
userStore.playerId(player),
count,
null,
new TranslatableComponent("gizmo.gun.raindropsResult"),
false
);
}));
} finally {
gifts.clear();
}
}
示例5: onEnable
import java.util.HashMap; //導入方法依賴的package包/類
public void onEnable(){
plugin = this;
this.getLogger().notice("WorldProtect is enable");
this.getServer().getPluginManager().registerEvents(new EventListener(),this);
this.config = new Config(this.getDataFolder()+"/worlds.yml",Config.YAML);
if (!this.config.exists("worlds")){
this.config.set("#worlds(保護列表)","#世界名稱,分割(英文)");
this.config.set("worlds","");
this.config.set("createmode","false");
this.config.save();
}
HashMap<String, String> permissions = new HashMap<>();
permissions.put("world.protect.command.worldprotectcommand", "op");
permissions.forEach((name, permission) -> Server.getInstance().getPluginManager().addPermission(new Permission(name, permission)));
Server.getInstance().getCommandMap().register("", new WorldProtectCommand());
List<String> list = new ArrayList<>();
list.addAll(Arrays.asList(this.config.get("worlds").toString().split(",")));
this.worlds = list;
}
示例6: saveDroitProfil
import java.util.HashMap; //導入方法依賴的package包/類
/** Enregistre un droit profil
* @param droitProfil
* @param fonctionnaliteMap
*/
public void saveDroitProfil(DroitProfil droitProfil, HashMap<DroitFonctionnalite, Boolean> fonctionnaliteMap) {
Assert.notNull(droitProfil, applicationContext.getMessage("assert.notNull", null, UI.getCurrent().getLocale()));
/* Verrou */
if (droitProfil.getIdProfil()!=null && !lockController.getLockOrNotify(droitProfil, null)) {
return;
}
final DroitProfil droitProfilSaved = droitProfilRepository.saveAndFlush(droitProfil);
droitProfilSaved.getDroitProfilFoncs().clear();
fonctionnaliteMap.forEach((k,v)->droitProfilSaved.addFonctionnalite(new DroitProfilFonc(k,droitProfilSaved,v)));
/*on met a jour la date pour que l'entity soit push*/
droitProfilSaved.setDatModProfil(LocalDateTime.now());
droitProfilRepository.saveAndFlush(droitProfilSaved);
lockController.releaseLock(droitProfilSaved);
}
示例7: getSchemaFromModel
import java.util.HashMap; //導入方法依賴的package包/類
private void getSchemaFromModel(Model model) {
HashMap<String, Property> references = getAllSchemaReferencesFromModel(model);
references.forEach((modelKey, property) -> {
String simpleRef = null;
Boolean isArray = false;
if (property instanceof RefProperty) {
simpleRef = ((RefProperty) property).getSimpleRef();
} else {
Property items = ((ArrayProperty) property).getItems();
if (items instanceof RefProperty) {
simpleRef = ((RefProperty) items).getSimpleRef();
} else {
return;
}
}
if (simpleRef != null) {
getDefinationsFromSchemaReference(simpleRef, modelKey);
}
});
}
示例8: getZipEntryNames
import java.util.HashMap; //導入方法依賴的package包/類
public static TreeMap<String, TreeMap<String, String>> getZipEntryNames(HashMap<String, File> extrasZipFilesMap) {
final TreeMap<String, TreeMap<String, String>> zipEntries = new TreeMap<String, TreeMap<String, String>>();
extrasZipFilesMap.forEach((key, file) -> {
zipEntries.put(key, getZipEntries(file.getAbsolutePath()));
});
return zipEntries;
}
示例9: execute
import java.util.HashMap; //導入方法依賴的package包/類
/**
* Callback for the execution of a command.
*
* @param src The commander who is executing this command
* @param args The parsed command arguments for this command
* @return the result of executing this command
* @throws CommandException If a user-facing error occurs while executing this command
*/
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
if (!(src instanceof Player))
return execServer(src, args);
HashMap<Player, UUID> deleteQueue = Maps.newHashMap();
Player player = (Player) src;
if (args.hasAny(ALL)) {
player.sendMessage(Text.of(
TextColors.GOLD, "Are you sure you want to unload all? ",
TextColors.GREEN, Text.builder("Yes ").onClick(TextActions.executeCallback(unloadAll(player))),
TextColors.RED, Text.builder("No").onClick(TextActions
.executeCallback(s -> player.sendMessage(Text.of(TextColors.GREEN, "Unload All Cancelled."))))
));
return CommandResult.success();
}
dataStore.getPlayerRegions(player).forEach(region ->
region.getChunks().forEach(chunk -> {
if (player.getLocation().getChunkPosition().equals(chunk.getPosition())) {
region.unForceChunks();
region.invalidateTicket();
deleteQueue.put(player, region.getUniqueId());
player.sendMessage(Text.of(TextColors.GREEN, "Successfully removed loaded region"));
}
}
));
// Delete all the regions queued to be deleted
deleteQueue.forEach((owner, regionId) -> dataStore.deletePlayerRegion(owner, regionId));
return CommandResult.success();
}
示例10: getOrderItemList
import java.util.HashMap; //導入方法依賴的package包/類
private List<OrderItem> getOrderItemList(com.jrtechnologies.yum.data.entity.DailyMenu dailyMenuEntity, Long userId) {
List<OrderItem> orderItemList = new ArrayList<OrderItem>();
HashMap<Long, Integer> foodQtys = new HashMap<>();
// get all orders
List<DailyOrder> dailyOrderEntities = dailyMenuEntity.getDailyOrders();
for(DailyOrder doe : dailyOrderEntities){
if(userId==ALL_USERS || doe.getUserId()==userId){
List<com.jrtechnologies.yum.data.entity.OrderItem> orderItems = doe.getOrderItems();
for(com.jrtechnologies.yum.data.entity.OrderItem orderItemEntity : orderItems){
Long foodId = orderItemEntity.getFood().getId();
foodQtys.put(foodId, (foodQtys.get(foodId)==null?0:foodQtys.get(foodId)) + orderItemEntity.getQuantity());
}
}
}
foodQtys.forEach((k,v)->{
OrderItem orderItem = new OrderItem();
orderItem.setFoodId(k);
orderItem.setQuantity(v);
//System.out.println("Item : " + k + " Count : " + v);
orderItemList.add(orderItem);
});
return orderItemList;
}
示例11: initCommand
import java.util.HashMap; //導入方法依賴的package包/類
private void initCommand(){
HashMap<String, String> permissions = new HashMap<>();
permissions.put("DontTapTheWhiteTile.Command.SetGame", "op");
permissions.put("DontTapTheWhiteTile.Command.DelGame", "op");
permissions.forEach((name, permission) -> Server.getInstance().getPluginManager().addPermission(new Permission(name, permission)));
Server.getInstance().getCommandMap().register("", new SetGame());
Server.getInstance().getCommandMap().register("", new DelGame());
}
示例12: main
import java.util.HashMap; //導入方法依賴的package包/類
public static void main(String args[]) throws IOException {
// Function
intIs = i -> new StringBuilder("Integer is: ").append(String.valueOf(i)).toString();
System.out.println(intIs.apply(121));
// UnaryOperator
UnaryOperator<Integer> randInt = x -> (int) (Math.random() * 100);
// Supplier
printInt(() -> 78);
printInt(FunctionalFace::doubleInt);
// Consumer
Consumer<Integer> com = x -> System.out.println(intIs.apply(x));
com.accept(randInt.apply(100));
com.accept(101);
// Predicate
Predicate<Integer> oe = x -> x % 2 == 0;
oddEvent(randInt.apply(50), oe);
oddEvent(127, oe);
// BiConsumer
HashMap<String, String> hash = new HashMap<>();
hash.put("cat", "orange");
hash.put("dog", "black");
hash.put("snake", "green");
// Use lambda expression that matches BiConsumer to display HashMap.
hash.forEach((string1, string2) -> System.out.println(string1 + "..."
+ string2 + ", " + string1.length()));
}
示例13: read
import java.util.HashMap; //導入方法依賴的package包/類
@Override
public DefaultAnnotations read(Kryo kryo, Input input, Class<DefaultAnnotations> type) {
DefaultAnnotations.Builder b = DefaultAnnotations.builder();
HashMap<String, String> map = kryo.readObject(input, HashMap.class);
map.forEach((k, v) -> b.set(k, v));
return b.build();
}
示例14: listAttributes
import java.util.HashMap; //導入方法依賴的package包/類
/**
* Best effort implementation of {@link N5Reader#listAttributes(String)}
* with limited type resolution. Possible return types are
* <ul>
* <li>null</li>
* <li>boolean</li>
* <li>double</li>
* <li>String</li>
* <li>Object</li>
* <li>boolean[]</li>
* <li>double[]</li>
* <li>String[]</li>
* <li>Object[]</li>
* </ul>
*/
@Override
public default Map<String, Class<?>> listAttributes(String pathName) throws IOException {
HashMap<String, JsonElement> jsonElementMap = getAttributes(pathName);
final HashMap<String, Class<?>> attributes = new HashMap<>();
jsonElementMap.forEach(
(key, jsonElement) -> {
final Class<?> clazz;
if (jsonElement.isJsonNull())
clazz = null;
else if (jsonElement.isJsonPrimitive())
clazz = classForJsonPrimitive((JsonPrimitive)jsonElement);
else if (jsonElement.isJsonArray()) {
final JsonArray jsonArray = (JsonArray)jsonElement;
if (jsonArray.size() > 0) {
final JsonElement firstElement = jsonArray.get(0);
if (firstElement.isJsonPrimitive())
clazz = Array.newInstance(classForJsonPrimitive((JsonPrimitive)firstElement), 0).getClass();
else
clazz = Object[].class;
}
else
clazz = Object[].class;
}
else
clazz = Object.class;
attributes.put(key, clazz);
});
return attributes;
}
示例15: sendPostRequest
import java.util.HashMap; //導入方法依賴的package包/類
public JSONObject sendPostRequest(HashMap<String, String> data, String url) {
if(!netIsAvailable()){
JOptionPane.showMessageDialog(null, "Internet connection error !", "Error", JOptionPane.ERROR_MESSAGE);
return null;
}
HttpClient httpClient = HttpClientBuilder.create().build();
try {
HttpPost request = new HttpPost(url);
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
data.forEach((k, v) -> {
urlParameters.add(new BasicNameValuePair(k, v));
});
request.setEntity(new UrlEncodedFormEntity(urlParameters));
request.addHeader("content-type", "application/x-www-form-urlencoded");
HttpResponse response = httpClient.execute(request);
if (response.getStatusLine().getStatusCode() == 404)
return null;
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
JSONObject obj = new JSONObject(result.toString());
return obj;
} catch (Exception ex) {
ex.printStackTrace();
return null;
} finally {
}
}