数据格式
1.有多个集合,每个集合的元素为字符串,字符串内容为key=value形式。
2.每个集合里的元素里的key都相同,只有value不同,比如
A集合的元素为"A=A1""A=A2"“A=A3”…
B集合的元素为"B=B1"“B=B2”…
C集合的元素为"C=C1""C=C2"“C=C3”…
需求
1.依次从每个集合中获取一个元素,将获取的多个元素组装为一个字符串,字符串内容为"A=A1:B=B1:C=C1"这样的形式。
2.组成的字符串具有唯一性
3.列举出所有的唯一性字符串
实现
1.使用component类封装集合,并具有父子关系
private static class Compoment{
//集合
private List<String> kvs;
//当前Compoment的子节点
private Compoment child;
public List<String> getKvs() {
return kvs;
}
public void setKvs(List<String> kvs) {
this.kvs = kvs;
}
public Compoment getChild() {
return child;
}
public void setChild(Compoment child) {
this.child = child;
}
}
2.使用递归,寻找至最后一个子节点
private static void get(Compoment compoment, StringBuffer sb, String parentKv){
for (String kv : compoment.getKvs()) {
String prefix = "";
if(!StringUtils.isEmpty(parentKv)){
prefix = parentKv + ":" + kv;
}else {
prefix = kv;
}
if(compoment.getChild() != null){
get(compoment.getChild(), sb, prefix);
}else {
sb.append(parentKv + ":" +kv);
sb.append("\n");
}
}
}
3.测试
public static void main(String[] args) {
Compoment parent = new Compoment();
parent.setKvs(Arrays.stream("A=A1,A=A2".split(",")).collect(Collectors.toList()));
Compoment child = new Compoment();
child.setKvs(Arrays.stream("B=B1,B=B2".split(",")).collect(Collectors.toList()));
parent.setChild(child);
Compoment son = new Compoment();
son.setKvs(Arrays.stream("C=C1,C=C2,C=C3".split(",")).collect(Collectors.toList()));
child.setChild(son);
StringBuffer sb = new StringBuffer();
get(parent, sb, "");
System.out.println(sb.toString());
}
打印结果为
A=A1:B=B1:C=C1
A=A1:B=B1:C=C2
A=A1:B=B1:C=C3
A=A1:B=B2:C=C1
A=A1:B=B2:C=C2
A=A1:B=B2:C=C3
A=A2:B=B1:C=C1
A=A2:B=B1:C=C2
A=A2:B=B1:C=C3
A=A2:B=B2:C=C1
A=A2:B=B2:C=C2
A=A2:B=B2:C=C3