我有一个列表列表:
List<ArrayList<String>> D = new ArrayList<>();
填充后,它可能看起来像:
[“A”、“B”、“Y”]
["C", "D", "Y"]
[“A”、“D”、“N”]
我想根据唯一的属性值(假设索引 1)将列表的列表拆分为多个分区。
所以索引 1 处的属性有两个唯一值,“B”和“D”,所以我想拆分为:
[“A”、“B”、“Y”]
[“C”、“D”、“Y”]
[“A”、“D”、“N”]
然后将它们放入 List<ArrayList<ArrayList<String>>> sublists;
中
有没有一种聪明的方法可以做到这一点,或者我只是做这样的事情:
List<ArrayList<ArrayList<String>>> sublists = new ArrayList<>();
int featIdx = 1;
// generate the subsets
for (ArrayList<String> record : D) {
String val = record.get(featIdx);
// check if the value exists in sublists
boolean found = false;
for (ArrayList<ArrayList<String>> entry : sublists) {
if (entry.get(0).get(featIdx).equals(val)) {
entry.add(record);
found = true;
break;
}
}
if (!found) {
sublists.add(new ArrayList<>());
sublists.get(sublists.size()-1).add(record);
}
}
这是 C4.5 决策树的一个步骤 algorithm ,所以如果有人有这方面的经验,请告诉我这是否是生成子列表的正确方法,我将不胜感激。
谢谢。
最佳答案
在 Java 8 中,您可以使用 groupingBy
收集器:
Map<String, List<List<String>>> grouped = D.stream()
.collect(Collectors.groupingBy(list -> list.get(1)));
Collection<List<List<String>>> sublists = grouped.values();
或按照@AlexisC 的建议:
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.groupingBy;
Collection<List<List<String>>> sublists = D.stream()
.collect(collectingAndThen(groupingBy(list -> list.get(1)), Map::values));
关于java - 根据唯一值将列表拆分为子列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28993068/