我有一个类:
public class myObj {
private boolean liesIn;
private String Area;
public myObj(){
}
public myObj(boolean liesIn, String Area) {
super();
this.liesIn = liesIn;
this.Area = Area;
}
public boolean isLiesIn() {
return liesIn;
}
public void setLiesIn(boolean liesIn) {
this.liesIn = liesIn;
}
public String getArea() {
return Area;
}
public void setArea(String Area) {
this.Area = Area;
}
}
我正在用这些对象填充一个列表:
List<myObj> results = new ArrayList<myObj>();
for (int i = 0; i < 10; i++) {
myObj theObj = new myObj();
theObj.setLiesIn(condition);
if (condition) {
theObj.setArea(Areas.values()[i].name());
results.add(theObj);
} else {
theObj.setArea("No area");
results.add(theObj);
}
}
现在,问题是,例如,我可能有 1 个 true 和 9 个 false,在退出时(当我返回结果时),我得到的所有结果/对象如下:
[
{
"liesIn": false,
"Area": "No area"
},
{
"liesIn": false,
"Area": "No area"
},
{
"liesIn": true,
"Area": "Area13"
},
{
"liesIn": false,
"Area": "No area"
},
{
"liesIn": true,
"Area": "Area14"
},
....
]
所以,如果我有真值,我只想显示它们。显示假值是没有意义的。
如果所有值都为 false,我只想显示一个结果。
我想创建一个新的结果列表并在旧列表中使用迭代器:
List<myObj> newresults = new ArrayList<myObj>();
Iterator<myObj> iter = results.iterator();
while (iter.hasNext()) {
myObj lies = iter.next();
if (lies.isLiesIn() == true) {
newresults.add(lies);
} else {
// add only 1 object with false value (no area)
}
}
所以,我不确定如何处理最后一段代码。也许还有另一种方法可以做到这一点。我想到使用复制来将结果
复制到newresults
但我再次无法处理 else 语句。
最佳答案
这不是问题 - 您需要做的就是:
List<myObj> newresults = new ArrayList<myObj>();
Iterator<myObj> iter = results.iterator();
while (iter.hasNext()) {
myObj lies = iter.next();
if (lies.isLiesIn() == true) {
newresults.add(lies);
}
}
// if no true element was added - the list contained only false
if (newresults.size()==0 && results.size()>0) {
newresults.add(results.get(0));
}
关于java - 如果列表项为 false,则仅在另一个列表中添加一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45935139/