<Java基础语法>List<Map>中删除某个元素key

直接上代码:
例如:下面这个List>,删除每个Map中:key为:"苹果手机"的元素;

package com.itheima;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class TestDemo {
	public static void main(String[] args) {
		  List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		  Map<String, String> map1=new HashMap<>(); 
		  map1.put("苹果手机","2");//添加键值对
		  map1.put("智能手表","1");
		  map1.put("java书","1");
		  map1.put("c语言书","1");
		  map1.put("西瓜","2");
		  Map<String, String> map2=new HashMap<>(); 
		  map2.put("苹果手机","20");//添加键值对
		  map2.put("智能手表","10");
		  map2.put("java书","10");
		  map2.put("c语言书","10");
		  map2.put("西瓜","20");
		  
		  list.add(map1);
		  list.add(map2);
		  
		  for (Map<String, String> map : list) {
			  System.out.println(map); 
		  }
		  
		  System.out.println("--------------------------------");  
		  
		  for (Map<String, String> map : list) {
		   Set<String> set = map.keySet();
	         Iterator<String> it = set.iterator();
	         while (it.hasNext()){
	             String key = it.next();
	             if (key.equals("苹果手机")) {
	                 it.remove();
	             }
	         }
	         System.out.println(map); 
		}		   
	}
}

测试输出:

{智能手表=1, java书=1, 苹果手机=2, c语言书=1, 西瓜=2}
{智能手表=10, java书=10, 苹果手机=20, c语言书=10, 西瓜=20}
--------------------------------
{智能手表=1, java书=1, c语言书=1, 西瓜=2}
{智能手表=10, java书=10, c语言书=10, 西瓜=20}

你可能感兴趣的:(java,ListMap,java,list,开发语言)