假设我有这个数据集:
1 A AA
1 A BB
1 A CC
2 C AA
3 A DD
3 W CC
4 W DD
我在一个CSV里找到了这个。如何在Java中按第一列对此进行分组,如:
1 A AA;BB;CC
2 C AA
3 A DD
3 W CC
4 W DD
我只有这个代码:
String[] array = new array[5]; //to fill with the new dataset
PrintWriter p = new PrintWriter(new File("TABLE.csv")); //the first dataset
StringBuilder sb = new StringBuilder();
for (int i = 0; i < )
{
sb.append(array[1]);
sb.append(',');
sb.append(array[1]);
sb.append(',');
}
在第一篇专栏文章的基础上,我该如何连接所有的最后一篇专栏呢?
发布于 2016-10-16 09:29:23
您想要做的是创建一个Map<‘结对,LinkedList<'String>>对象来收集您的数据,其中结对是一个表示前两列的类。给我几分钟时间,我会带一些代码回来给您看。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class Main {
public static void main(String args[]) throws FileNotFoundException {
// Scanner scanner = new Scanner(System.in);
Scanner scanner = new Scanner(new File("TABLE.csv"));
Map<Pair, List<String>> output = new HashMap<Pair, List<String>>();
while (scanner.hasNext()) {
String col1 = scanner.next();
String col2 = scanner.next();
String value = scanner.next();
Pair pair = new Pair(col1, col2);
if (output.containsKey(pair)) {
output.get(pair).add(value);
} else {
output.put(pair, new LinkedList<String>());
output.get(pair).add(value);
}
}
System.out.println(output.toString());
}
}
class Pair {
private String col1;
@Override
public String toString() {
return "Pair{" +
"col1='" + col1 + '\'' +
", col2='" + col2 + '\'' +
'}';
}
public Pair(String col1, String col2) {
this.col1 = col1;
this.col2 = col2;
}
private String col2;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair pair = (Pair) o;
if (col1 != null ? !col1.equals(pair.col1) : pair.col1 != null) return false;
return col2 != null ? col2.equals(pair.col2) : pair.col2 == null;
}
@Override
public int hashCode() {
int result = col1 != null ? col1.hashCode() : 0;
result = 31 * result + (col2 != null ? col2.hashCode() : 0);
return result;
}
}
这不是一个完美的解决方案,但它有效,会让你在某个地方开始工作。考虑添加某种类型的输入错误处理,此代码假设每次输入都是完美的。
https://stackoverflow.com/questions/40073063
复制相似问题