我有一个json对象类型arraylist,并且jsonobject包含字符串和布尔值。现在我的要求是按顺序设置具有真实值的arraylist。将所有包含真实值的jsonobject放在顶部,所以我该如何更改arraylist的顺序按特定值。 假设我有清单 {matched:true},{matched:false},{matched:true},{matched:false},{matched:false},{matched:true}。 但我想要清单 {matched:true},{matched:true},{matched:true},{matched:false},{matched:false},{matched:false}。 使用langugae Java。
答案 0 :(得分:0)
在科特林:
val list = arrayListOf(false, true, false, true, false)
list.sortBy { it == false }
输出:
[true, true, false, false, false]
这是一个示例,如果我们要根据对象进行排序:
// Your model class
class SomeObject(var value: String, var state: Boolean)
...
val list = arrayListOf<SomeObject>(
SomeObject("some value", false),
SomeObject("some value2", true),
SomeObject("some value3", false),
SomeObject("some value4", false),
SomeObject("some value5", true))
list.sortBy { it.state == false }
在Java中:
// Model ->
public class SomeObject {
private String name;
private Boolean state;
public SomeObject(String name, Boolean state) {
this.name = name;
this.state = state;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Boolean getState() {
return state;
}
public void setState(Boolean state) {
this.state = state;
}
}
...
ArrayList<SomeObject> list = new ArrayList<>();
list.add(new SomeObject("some value", false));
list.add(new SomeObject("some value2", true));
list.add(new SomeObject("some value3", false));
list.add(new SomeObject("some value4", false));
list.add(new SomeObject("some value5", true));
list.sort((o1, o2) -> Boolean.compare(!o1.getState(), !o2.getState()));
list.forEach((it) -> System.out.println(it.getState()));
输出:
[true, true, false, false, false]