2 回答
TA贡献1872条经验 获得超3个赞
我希望下面的这段代码能帮助你:)我
做什么,我首先为每一行创建一个对象。之后,我将每个对象与我想与之比较的那行的键进行比较。这样,您也可以选择要比较的“CSV密钥”。
您可以使用此代码,但请记住,我在那里放置了2个“TODO”,如果您不考虑它们,这些可能是空指针异常:)
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* @author runef
*/
public class Test {
public static void main(String[] args) {
new Test();
}
private List<CoolObject> coolObjects = new ArrayList<>();
private String[] linesOfCSV = {"A,B,C,D", "1,2,A,A", "2,1,B,B"};
public Test() {
String[] keys = null;
for (String s : linesOfCSV) {
String[] lineValues = s.split(",");
if (keys == null) {
keys = lineValues;
} else {
Map<String, String> aGoodName = new HashMap<>();
for (int i = 0; i < lineValues.length; i++) {
//TODO: Check if keys[i] exists, check if lineValues[i] exists (if not probs something wrong with CSV)
aGoodName.put(keys[i], lineValues[i]);
}
coolObjects.add(new CoolObject(aGoodName));
}
}
Collections.sort(coolObjects, new SortByKey("A"));
System.out.println("SORTED BY KEY 'A'");
for (CoolObject o : coolObjects) {
for (Map.Entry<String, String> entry : o.getACoolMap().entrySet()) {
System.out.print(entry.getKey() + ": " + entry.getValue() + " ");
}
System.out.print("\n");
}
Collections.sort(coolObjects, new SortByKey("B"));
System.out.println("SORTED BY KEY 'B'");
for (CoolObject o : coolObjects) {
for (Map.Entry<String, String> entry : o.getACoolMap().entrySet()) {
System.out.print(entry.getKey() + ": " + entry.getValue() + " ");
}
System.out.print("\n");
}
}
class CoolObject {
private Map<String, String> aCoolMap;
public CoolObject(Map<String, String> aCoolMap) {
this.aCoolMap = aCoolMap;
}
public Map<String, String> getACoolMap() {
return aCoolMap;
}
}
class SortByKey implements Comparator<CoolObject> {
private String keySorter;
public SortByKey(String keySorter) {
this.keySorter = keySorter;
}
public int compare(CoolObject a, CoolObject b) {
//TODO: CHECK IF KEY EXISTS IN BOTH VALUES! ELSE DO SOMETHING ELSE :) PROBS RETURN -1 SO IT COMES LAST!
return a.getACoolMap().get(this.keySorter).hashCode() - b.getACoolMap().get(this.keySorter).hashCode();
}
}
}
TA贡献1820条经验 获得超10个赞
这将对一列进行排序。您可以修改它以用于多个列。
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
public class Test {
public static void main(String[] args) throws IOException {
ArrayList<String> list = new ArrayList<>();
int lineNumber = 0;
File csvFile = new File("D://new.csv");
BufferedReader br = new BufferedReader(new FileReader(csvFile));
String line = "";
while ((line = br.readLine()) != null) {
String[] arr = line.split(",");
list.add(arr[0]);
lineNumber++;
}
Collections.sort(list);
list.forEach(i -> System.out.println(i));
}
}
添加回答
举报