當前位置: 首頁>>代碼示例>>Java>>正文


Java HashMap.forEach方法代碼示例

本文整理匯總了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();
}
 
開發者ID:Obsidiam,項目名稱:amelia,代碼行數:21,代碼來源:XMLController.java

示例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;
    }
}
 
開發者ID:Panzer1119,項目名稱:Supreme-Bot,代碼行數:22,代碼來源:Util.java

示例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);
        }
    });
}
 
開發者ID:slavetto,項目名稱:anki-cards-web-browser,代碼行數:19,代碼來源:Exporter.java

示例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();
    }
}
 
開發者ID:OvercastNetwork,項目名稱:ProjectAres,代碼行數:20,代碼來源:GunGizmo.java

示例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;
}
 
開發者ID:MamoeTech,項目名稱:Nukkit-WorldProtect,代碼行數:22,代碼來源:WorldProtect.java

示例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);
}
 
開發者ID:EsupPortail,項目名稱:esup-ecandidat,代碼行數:22,代碼來源:DroitProfilController.java

示例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);
        }

    });
}
 
開發者ID:bsneha90,項目名稱:RecursiveSwaggerSchemaParser,代碼行數:23,代碼來源:SwaggerParserHelper.java

示例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;
}
 
開發者ID:phweda,項目名稱:MFM,代碼行數:8,代碼來源:ZipUtils.java

示例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();
}
 
開發者ID:DevOnTheRocks,項目名稱:StickyChunk,代碼行數:42,代碼來源:CommandUnload.java

示例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;
    }
 
開發者ID:jrtechnologies,項目名稱:yum,代碼行數:31,代碼來源:ChefOrdersService.java

示例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());
}
 
開發者ID:WetABQ,項目名稱:Nukkit-DontTapTheWhiteTile,代碼行數:9,代碼來源:DontTapTheWhiteTile.java

示例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()));                      
    }
 
開發者ID:mkdika,項目名稱:learnjava8,代碼行數:33,代碼來源:FunctionalFace.java

示例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();
}
 
開發者ID:shlee89,項目名稱:athena,代碼行數:9,代碼來源:AnnotationsSerializer.java

示例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;
}
 
開發者ID:saalfeldlab,項目名稱:n5,代碼行數:46,代碼來源:GsonAttributesParser.java

示例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 {

	}
}
 
開發者ID:alireza6677,項目名稱:BestoonGui,代碼行數:43,代碼來源:Connection.java


注:本文中的java.util.HashMap.forEach方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。