英文:
Hash Map object list iteration using Java 8 Streams
问题
我必须迭代HashMap对象列表。如果映射对象的值为true,则必须使用Java 8 Stream API将该条目返回到一个映射哈希对象中。
public class HashMapCheck {
    static Map<String, Boolean> map;
    static Map<String, Boolean> map2;
    static List<Map> objMap;
    public static void main(String args[]) {
        map = new HashMap<String, Boolean>();
        map.put("1", true);
        map.put("2", false);
        map2 = new HashMap<String, Boolean>();
        map2.put("4", true);
        map2.put("5", true);
        objMap = new ArrayList<Map>();
        objMap.add(map);
        objMap.add(map2);
        // 迭代部分
    }
}
英文:
I have to iterate the HashMap object list. if the map object value is true then I have to return that entry to one map Hash object using java 8 stream API
public class HashMapCheck {
	static Map<String, Boolean> map;
	static Map<String, Boolean> map2;
	static List<Map> objMap;
	public static void main(String args[]) {
		map = new HashMap<String, Boolean>();
		map.put("1", true);
		map.put("2", false);
		map2 = new HashMap<String, Boolean>();
		map2.put("4", true);
		map2.put("5", true);
		objMap = new ArrayList<Map>();
		objMap.add(map);
		objMap.add(map2);
		//Iterate
	}
}
答案1
得分: 0
我对Java流处理不是很熟悉,所以也许这不是最简洁的解决方案,但以下是我使用流处理想出来的代码,以获取我认为你想要的结果:
public class HashMapCheck {
    static Map<String, Boolean> map;
    static Map<String, Boolean> map2;
    static List<Map<String, Boolean>> objMap;
    public static void main(String[] args) {
        map = new HashMap<>();
        map.put("1", true);
        map.put("2", false);
        map2 = new HashMap<>();
        map2.put("4", true);
        map2.put("5", true);
        objMap = new ArrayList<>();
        objMap.add(map);
        objMap.add(map2);
        Map<String, Boolean> result = objMap.stream().flatMap(x -> x.entrySet().stream()).filter(Map.Entry::getValue).
                collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        System.out.println(result);
    }
}
结果:
{1=true, 4=true, 5=true}
英文:
I'm not an expert with Java streams, so maybe this is not the minimal solution, but here's what I came up with using streams to get what I think you want:
public class HashMapCheck {
    static Map<String, Boolean> map;
    static Map<String, Boolean> map2;
    static List<Map<String, Boolean>> objMap;
    public static void main(String[] args) {
        map = new HashMap<>();
        map.put("1", true);
        map.put("2", false);
        map2 = new HashMap<>();
        map2.put("4", true);
        map2.put("5", true);
        objMap = new ArrayList<>();
        objMap.add(map);
        objMap.add(map2);
        Map<String, Boolean> result = objMap.stream().flatMap(x -> x.entrySet().stream()).filter(Map.Entry::getValue).
                collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        System.out.println(result);
    }
}
Result:
{1=true, 4=true, 5=true}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论