62,634
社区成员




@Data
class Key {
private String k;
private List<Key> list;
}
public class Test {
public static void main(String[] args) {
List<String> strList = Arrays.asList(
"信息部,IT组,张三",
"信息部,IT组,李四",
"信息部,运维组,王五",
"科技部,研发组,赵六");
List<Key> list = new ArrayList<>();
// TODO 请填写此处代码
System.out.println(JSON.toJSONString(list));
}
}
public class Test {
public static void main(String[] args) {
List<String> strList = Arrays.asList(
"信息部,IT组,张三",
"信息部,IT组,李四",
"信息部,运维组,王五",
"科技部,研发组,赵六");
List<Key> list = new ArrayList<>();
// TODO 请填写此处代码
for (String s : strList) { //字符串list循环
String[] arr = s.split(","); //字符串分割
List<Key> ll = list;
for (int i=0; i<arr.length; i++) { //分别判断分割后的字符串在结果list的k是否存在
Key key = null;
for (Key k : ll) {
if (arr[i].equals(k.getK())) {
key = k;
break;
}
}
if (key == null) { //如果不存在,new一个Key放到结果list里
key = new Key();
key.setK(arr[i]);
ll.add(key);
for (int j=i+1; j<arr.length; j++) { //其实主要就是循环生成list
ll = new ArrayList<>();
key.setList(ll);
key = new Key();
key.setK(arr[j]);
ll.add(key);
}
break;
}
ll = key.getList(); //如果存在,继续判断key.list里是否存在下一个分割的字符串
if (ll == null) {
ll = new ArrayList<>();
key.setList(ll);
}
}
}
System.out.println(JSON.toJSONString(list));
}
}
public static void main(String[] args) {
List<String> strList = Arrays.asList(
"信息部,IT组,张三",
"信息部,IT组,李四",
"信息部,运维组,王五",
"科技部,研发组,赵六");
List<Key> list = new ArrayList<>();
// TODO 请填写此处代码
String[] split = null;
for(String str:strList){
split = str.split(",");
f(0,split,list);
}
System.out.println(JSON.toJSONString(list));
}
private static void f(int i,String [] split,List<Key> list){
Key key = null;
if(i==split.length){
key = getKey(split[i-1], list);
if(null != key){
key.setList(null);
}
return;
}
if(null == list){
list = new ArrayList<>();
}
key = getKey(split[i], list);
if(null == key){
key = new Key();
key.setK(split[i]);
key.setList(new ArrayList<>());
list.add(key);
}
f(i+1,split,key.getList());
}
private static Key getKey(String keyStr,List<Key> list){
for (int i=0;i<list.size();i++){
if(list.get(i).getK().equals(keyStr)){
return list.get(i);
}
}
return null;
}