3 回答

TA貢獻1836條經(jīng)驗 獲得超4個贊
將逗號分隔的值放入LinkedHashMap
TreeMap<String, Double> map = new LinkedHashMap<String, Double>();
try (BufferedReader br = Files.newBufferedReader(Paths.get("yourfile.csv"))) {
String line;
while ((line = br.readLine()) != null) {
String[] parts = line.split(";");
map.put(parts[0], Double.parseDouble(parts[1]));
}
}
catch (IOException e) {
System.err.format("IOException: %s%n", e);
}
map然后根據(jù)雙精度值排序。
嘗試使用 java 8,
LinkedHashMap<String, Double> sortedMap;
sortedMap = map.entrySet().stream().sorted(Entry.comparingByValue()).collect(Collectors.toMap(Entry::getKey, Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));

TA貢獻1829條經(jīng)驗 獲得超13個贊
我們可以嘗試將文件解析為排序映射(例如TreeMap)的一般方法,然后迭代映射并寫回文件。
TreeMap<String, Double> map = new TreeMap<String, Double>();
try (BufferedReader br = Files.newBufferedReader(Paths.get("yourfile.csv"))) {
String line;
while ((line = br.readLine()) != null) {
String[] parts = line.split(";");
map.put(parts[0], Double.parseDouble(parts[1]));
}
}
catch (IOException e) {
System.err.format("IOException: %s%n", e);
}
// now write the map to file, sorted ascending in alphabetical order
try (FileWriter writer = new FileWriter("yourfileout.csv");
BufferedWriter bw = new BufferedWriter(writer)) {
for (Map.Entry<String, Double> entry : map.entrySet()) {
bw.write(entry.getKey() + ";" + entry.getValue());
}
}
catch (IOException e) {
System.err.format("IOException: %s%n", e);
}
筆記:
我假設第一列中的字符串值總是唯一的。如果可能存在重復,則必須修改上述腳本以使用列表映射或類似的東西。
我還假設字符串值都是小寫的。如果沒有,那么您可能無法獲得您期望的排序。如果這是一個問題,一種解決方案是在將該鍵插入映射之前將每個字符串小寫(或大寫)。

TA貢獻1856條經(jīng)驗 獲得超11個贊
將 CSV 文件讀入一個( CSV 文件中List的每行一個)Object[]Object[]
數(shù)組的第一個元素是行本身(一個字符串)
數(shù)組的第二個元素是 double 的值(一個 Double)
所以你有以下列表:
{
["tricolor;14.0", 14.0],
["career;9.0", 9.0],
["salty;1020.0", 1020.0],
["looks;208.0", 208.0],
["bought;110.0", 110.0]
}
然后根據(jù)double的值排序
然后您可以將其寫回 CSV 文件(僅寫入每個數(shù)組的第一個元素)
List<Object[]> list = readFile("myFile.csv");
list.sort(Comparator.comparing(p -> (Double)p[1]));
// write to csv file, just printing it out here
list.forEach(p -> System.out.println(p[0]));
讀取文件的方法:
private static List<Object[]> readFile(String fileName) {
List<Object[]> list = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
String[] splitLine;
while ((line = br.readLine()) != null) {
splitLine = line.split(";");
// add an array, first element is the line itself, second element is the double value
list.add(new Object[] {line, Double.valueOf(splitLine[1])});
}
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
編輯如果你想要相反的順序:
一旦你有你的排序列表,你可以使用類reverse上的方便方法來反轉(zhuǎn)它Collections
Collections.reverse(list);
添加回答
舉報