我有以下代码:
for(String s1 : source){
for(String s2 : target){
if(s1.length() > 4 && s2.length() > 4){
String sKey = s1.substring(1,5);
String tKey = s2.substring(1,5);
if(sKey.equals(tKey)){
//Do your logic...
}else if(!sKey.equals(tKey) && sKey not availlable in the target list){
//print the value that sKey not availlable in target
}
}
}
}
如果在列表的整个遍历中都找不到键,那么我需要打印该值。
请帮忙 !!
显而易见的解决方案是添加一个条件,并在最后检查该条件。
for(String s1 : source){
boolean found = false;
for(String s2 : target){
if(s1.length() > 4 && s2.length() > 4){
String sKey = s1.substring(1,5);
String tKey = s2.substring(1,5);
if(sKey.equals(tKey)){
found=true;
break;
}
}
}
if(found){
//found logic
} else{
//not found logic
}
}
问题在于,您每次都在创建一个新的子字符串。相反,我建议创建一个密钥列表。
List<String> targetKeys = target.stream().filter(
s->s.length()>4
).map(
s->s.substring(1,5)
).collect(Collectors.toList());
List<String> sourceKeys = source.stream().filter(
s->s.length()>4
).map(
s->s.substring(1,5)
).collect(Collectors.toList());
然后,您可以做类似的事情。
sourceKeys.removeAll(targetKeys);
您将只剩下不存在的键的位置。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句