编辑了半天又不显示了 靠.ssssss
public static void main(String[] args){
//构造数据
List<Data> list = new ArrayList<Data>();
list.add(new Data("三国志12", "03-01", "5"));
list.add(new Data("雷霆战机", "03-01", "2"));
list.add(new Data("真三国无双7", "03-02", "4"));
list.add(new Data("三国志12", "03-03", "5"));
list.add(new Data("雷霆战机", "03-04", "5"));
list.add(new Data("真三国无双7", "03-05", "5"));
String[][] tableData = toTable(list);
if (log.isDebugEnabled()){
log.debug(JsonUtil.format(tableData));
}
}
/**
* 将 config装成 二维数组 table.
*
* @param list
* the list
* @param nameComparator
* the name comparator
* @param keyComparator
* the key comparator
* @return the string[][]
*/
private static String[][] toTable(List<Data> list){
//这个问题的核心,是通过name和key 取到 value值
//因此,为了性能,设计一个map,这个map的key 是config的name和key拼接起来的
Map<String, Data> map = new LinkedHashMap<String, Data>();
//LinkedHashSet 保证循环的顺序
Set<String> nameSet = new LinkedHashSet<String>();
Set<String> keySet = new LinkedHashSet<String>();
for (Data config : list){
String key = config.getKey();
String name = config.getName();
nameSet.add(name);
keySet.add(key);
//确保map中的key不会重复
String k = key + "@" + name;
map.put(k, config);
}
int rowLength = list.size();
int columnLength = nameSet.size() + 1;
String[][] table = new String[rowLength][columnLength];
//第一行 放name 标题
table[0] = CollectionsUtil.toArray(nameSet);
int i = 0;
for (String key : keySet){
String[] array = new String[columnLength];
array[0] = key;
int j = 0;
for (String name : nameSet){
String k = key + "@" + name;
Data config = map.get(k);
String value = null;
if (null != config){
value = config.getValue();
}
array[j + 1] = value;
j++;
}
table[i + 1] = array;
i++;
}
return table;
}
13:34:00 DEBUG (CopyOfDataTest.java:90) [main()] [
[
"三国志12",
"雷霆战机",
"真三国无双7"
],
[
"03-01",
"5",
"2",
null
],
[
"03-02",
null,
null,
"4"
],
[
"03-03",
"5",
null,
null
],
[
"03-04",
null,
"5",
null
],
[
"03-05",
null,
null,
"5"
]
]