[英]how to restrict Java method invocation only for 1st occurance of any event?
[英]how to filter hashmap and find 1st occurance
我已经将我的哈希图转换为json,因为我不知道它在Java中是什么样子
所以我的哈希图看起来像
{"1":[true,false],
"2":[true,true],
"3":[true]}
我需要在单个键中获得数组列表中所有true的第一次出现
在这种情况下,它的2是第一次
因此,如果发生// //做其他事情//做其他事情
hm.forEach((key, value) -> {
for (Object object : value) {
boolean b = (boolean)object;
if(!b){
break;
}else{
System.out.println(key+"->"+b);
}
}
});
我尝试过这样的事情,但是我在这里的测试中迷失了很多
任何帮助将不胜感激
您可以使用此架构
hm.entrySet().stream().filter(SomeClass::isAllBoolean)
.findFirst()
.ifPresent(System.out::println);
private static boolean isAllBoolean(Map.Entry<String, List<Boolean>> values) {
}
SomeClass
是isAllBoolean
方法所在的类。
请尝试下面的代码段。
hm.forEach((key, value) -> {
boolean allTrue=true;
for (Object object : value) {
allTrue = (boolean)object;
if(!allTrue){ //stop if you found a false in the true/false array
break;
}
}//out of the inner iteration
if(allTrue){//if this variable is true, it means the above iteration had all values true
//do your stuff
break;
}
allTrue=true; //reset
});
显然,您需要一个filter
来检查一个全真布尔数组,一个findFirst
来查找第一个布尔数组,以及一个get
来处理findFirst
返回Optional
的事实。
public void test(String[] args) {
Map<String, Boolean[]> hm = new HashMap<>();
hm.put("1", new Boolean[]{true, false});
hm.put("2", new Boolean[]{true, true});
hm.put("3", new Boolean[]{true});
Map.Entry<String, Boolean[]> first = hm.entrySet().stream()
.filter(es -> allTrue(es.getValue()))
.findFirst()
.orElse(null);
System.out.println(first.getKey()+" -> "+ Arrays.toString(first.getValue()));
}
private boolean allTrue(Boolean[] a) {
for (Boolean b : a) {
if (!b) return false;
}
return true;
}
版画
2-> [true,true]
顺便说一句:未定义Map
的迭代顺序,因此您通过捕获first
一个来依赖未记录的功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.