Java Map中删除其中的元素,统计元素的个数
package TestFunction; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; public class Nums_Map { public static void main(String[] args) { HashMap<String, String> hmw = new HashMap<String, String>(); //add key-value pair to hashmap hmw.put("0,1,2", "FIRST "); hmw.put("3,4,5", "SECOND "); hmw.put("6,7,8","THIRD "); System.out.println("Map的信息:"); System.out.println(hmw); Set<String> keys = hmw.keySet(); System.out.println("Map的键信息:"); for(String key: keys){ System.out.println(key); } System.out.println(hmw.size()); System.out.println("======================================"); System.out.println("对键值进行分割,删除map 中的一些信息:"); Iterator<Map.Entry<String, String>> it = hmw.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> entry = it.next(); String[] s = entry.getKey().split(","); System.out.println(s[0] + s[1] + s[2]); if(s[0].equals("0")){ it.remove(); } if(s[2].equals("5")){ it.remove(); } } System.out.println("删除后map 的个数:"); System.out.println(hmw.size()); } }
结果展示:
Map的信息: {6,7,8=THIRD , 0,1,2=FIRST , 3,4,5=SECOND } Map的键信息: 6,7,8 0,1,2 3,4,5 3 ====================================== 对键值进行分割,删除map 中的一些信息: 678 012 345 删除后map 的个数: 1