在多层嵌套Map中查找值匹配的路径
2021-12-22 本文已影响0人
帕博雷克斯丢丢
package com.demos.practiceone.util;
import java.util.LinkedList;
import java.util.Map;
import java.util.Objects;
public class NestedMapFinder {
private final LinkedList<Object> orderChain = new LinkedList<>();
private boolean doesFindIt = false;
public boolean isFound() {
return this.doesFindIt;
}
public <T> LinkedList<?> find(Map<?, ?> map, T target) {
for (Map.Entry<?, ?> e : map.entrySet()) {
Object k = e.getKey();
Object v = e.getValue();
orderChain.add(k);
if ((target == null && v == null) || Objects.equals(target, v)) {
this.doesFindIt = true;
break;
} else {
if (v instanceof Map<?, ?>) {
this.find((Map<?, ?>) v, target);
} else {
orderChain.removeLast();
}
}
}
if (!this.doesFindIt && orderChain.size() != 0) {
orderChain.removeLast();
}
return orderChain;
}
}