当前位置: 首页>>代码示例>>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;未经允许,请勿转载。