java 删除树结构-末级&未被选中的子集和父级
代码
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class Test {
public static void main(String[] args) throws JsonProcessingException {
Person s1 = new Person("1-1", true, true, null);
Person s2 = new Person("1-2", false, true, null);
Person p1 = new Person("1", false, false, new ArrayList(Arrays.asList(s1, s2)));
Person s3 = new Person("2-1", false, true, null);
Person p2 = new Person("2", false, false, new ArrayList(Arrays.asList(s3)));
Person p3 = new Person("3", false, false, new ArrayList<>());
ObjectMapper mapper = new ObjectMapper();
List<Person> people = new ArrayList(Arrays.asList(p1, p2, p3));
System.out.println(mapper.writeValueAsString(people));
filter(people);
System.out.println(mapper.writeValueAsString(people));
}
public static void filter(List<Person> people) {
Iterator<Person> iterator = people.iterator();
while (iterator.hasNext()) {
Person next = iterator.next();
List<Person> chils = next.getChils();
if (!CollectionUtils.isEmpty(chils)) {
filter(chils);
}
Boolean remove = isRemove(next);
if (remove) {
iterator.remove();
}
}
}
public static Boolean isRemove(Person next) {
Boolean ismo = next.getIsmo();
Boolean ischeck = next.getIscheck();
List<Person> chils = next.getChils();
if (ismo) {
return !ischeck;
}
if (chils == null || chils.size() == 0) {
return true;
}
return false;
}
}
sout 第一次输出
[{"id":"1","ischeck":false,"ismo":false,"chils":[{"id":"1-1","ischeck":true,"ismo":true,"chils":null},{"id":"1-2","ischeck":false,"ismo":true,"chils":null}]},{"id":"2","ischeck":false,"ismo":false,"chils":[{"id":"2-1","ischeck":false,"ismo":false,"chils":null}]},{"id":"3","ischeck":false,"ismo":false,"chils":[]}]
sout 第二次输出
[{"id":"1","ischeck":false,"ismo":false,"chils":[{"id":"1-1","ischeck":true,"ismo":true,"chils":null}]}]
|