-
HUH函数
将逗号分隔的值放入LinkedHashMapTreeMap<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然后根据双精度值排序。尝试使用 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));
-
烙印99
我们可以尝试将文件解析为排序映射(例如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 ordertry (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);}笔记:我假设第一列中的字符串值总是唯一的。如果可能存在重复,则必须修改上述脚本以使用列表映射或类似的东西。我还假设字符串值都是小写的。如果没有,那么您可能无法获得您期望的排序。如果这是一个问题,一种解决方案是在将该键插入映射之前将每个字符串小写(或大写)。
-
呼唤远方
将 CSV 文件读入一个( CSV 文件中List的每行一个)Object[]Object[]数组的第一个元素是行本身(一个字符串)数组的第二个元素是 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]}然后根据double的值排序然后您可以将其写回 CSV 文件(仅写入每个数组的第一个元素)List<Object[]> list = readFile("myFile.csv");list.sort(Comparator.comparing(p -> (Double)p[1]));// write to csv file, just printing it out herelist.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上的方便方法来反转它CollectionsCollections.reverse(list);