需要生成结构如下
代码搞起
package com;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import org.hibernate.type.PrimitiveByteArrayBlobType;
import com.alibaba.fastjson.JSONObject;
import com.sun.javafx.collections.MappingChange.Map;
import com.sun.org.apache.xerces.internal.xs.ShortList;
public class Test {
private static List<String> list=new ArrayList<>();
static {
list.add("你好");
list.add("你好呀!");
list.add("你好吗?");
list.add("你好吗?你在干嘛!");
list.add("你好呀!你在干嘛?");
}
public static void getNode(HashMap<Node,List<String>> nodeMap) {
for (Entry<Node, List<String>> entry : nodeMap.entrySet()) {
Node node = entry.getKey();
List<String> valueList = entry.getValue();
valueList.sort(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return -Integer.compare(o1.length(),o2.length());
}
});
List<String> removeStrList=new ArrayList<>();
HashMap<Node,List<String>> newMap = new HashMap<Node,List<String>>();
for (String var : valueList) {
if(removeStrList.contains(var))
continue;
Node node2 = new Node(new ArrayList<Node>(), var);
node.getNodeList().add(node2);
List<String> newValues=new ArrayList<>();
newMap.put(node2, newValues);
for (String var2 : valueList) {
if(!var2.equals(var)&&var.contains(var2)) {
removeStrList.add(var2);
newValues.add(var2);
}
}
}
List<Node> nodeList = node.getNodeList();
for (Node node2 : nodeList) {
List<String> list2 = newMap.get(node2);
HashMap<Node,List<String>> tmpMap = new HashMap<Node,List<String>>();
tmpMap.put(node2, list2);
getNode(tmpMap);
}
}
}
public static void main(String[] args) {
HashMap<Node,List<String>> hashMap = new HashMap<Node,List<String>>();
Node node = new Node(new ArrayList<Node>(), null);
hashMap.put(node, list);
getNode(hashMap);
System.out.println(JSONObject.toJSONString(node));
}
}
class Node{
private List<Node> nodeList;
private String nodeValue;
public Node(List<Node> nodeList, String nodeValue) {
super();
this.nodeList = nodeList;
this.nodeValue = nodeValue;
}
public List<Node> getNodeList() {
return nodeList;
}
public void setNodeList(List<Node> nodeList) {
this.nodeList = nodeList;
}
public String getNodeValue() {
return nodeValue;
}
public void setNodeValue(String nodeValue) {
this.nodeValue = nodeValue;
}
@Override
public String toString() {
return "Node [nodeList=" + nodeList + ", nodeValue=" + nodeValue + "]";
}
}