Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中对CSV文件中的列进行排序_Java_Sorting_Csv - Fatal编程技术网

在Java中对CSV文件中的列进行排序

在Java中对CSV文件中的列进行排序,java,sorting,csv,Java,Sorting,Csv,我有一个CSV文件可以读取这个 City,Job,Salary Delhi,Doctors,500 Delhi,Lawyers,400 Delhi,Plumbers,100 London,Doctors,800 London,Lawyers,700 London,Plumbers,300 Tokyo,Doctors,900 Tokyo,Lawyers,800 Tokyo,Plumbers,400 Lawyers,Doctors,300 Lawyers,Lawyers,400 Lawyers,Pl

我有一个CSV文件可以读取这个

City,Job,Salary
Delhi,Doctors,500
Delhi,Lawyers,400
Delhi,Plumbers,100
London,Doctors,800
London,Lawyers,700
London,Plumbers,300
Tokyo,Doctors,900
Tokyo,Lawyers,800
Tokyo,Plumbers,400
Lawyers,Doctors,300
Lawyers,Lawyers,400
Lawyers,Plumbers,500
Hong Kong,Doctors,1800
Hong Kong,Lawyers,1100
Hong Kong,Plumbers,1000
Moscow,Doctors,300
Moscow,Lawyers,200
Moscow,Plumbers,100
Berlin,Doctors,800
Berlin,Plumbers,900
Paris,Doctors,900
Paris,Lawyers,800
Paris,Plumbers,500
Paris,Dog catchers,400`
现在,我想对Salary列进行排序并将其写入txt文件

我可以访问该列,但无法对其进行排序。我不熟悉Java的CSV阅读部分。有人能帮忙吗!如何将每个薪资值存储到变量中

import java.io.*;

public class Main {

    public static void main(String args[]) throws FileNotFoundException
    {
        String csv="C:\\Users\\Dipayan\\Desktop\\salaries.csv";
        BufferedReader br= new BufferedReader(new FileReader(csv));
        String line="";

        try {
            br.readLine();

            while((line = br.readLine())!=null)
            {
                String[] f=line.split(",");
                System.out.println(" Salary ="+f[2]);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

我想你们应该在这里用地图,否则可能会被发现

List<Integer, String> 
列表
如果是地图

 Map<Integer,String>
Map
其中key是salary,字符串是整行。 让我写一些代码来帮助你

 Map<Integer,String> dataMap = new HashMap<Integer,String>();
 String row = br.readLine();
 String columns[]=row.split(","); // columns[2] has the salary now
 dataMap.add(Integer.valueOf(columns[2]),row);
Map dataMap=newhashmap();
字符串行=br.readLine();
字符串列[]=行。拆分(“,”);//[2]列现在有工资
add(Integer.valueOf(columns[2]),row);
使用气泡排序查看内容,或使用客户比较类对地图进行排序。检查集合Api的可能排序函数

You can use even List<Integer,String>
您可以使用偶数列表
按照整数排序,将元素放在实际位置,然后重新生成文件

编辑:
您可以使用树映射,因为它对数据进行排序。只需使用整型树映射作为键,字符串作为值。把所有的值放进去,然后在上面迭代,就这样

您可以尝试以下方法-

String csv="/home/user/Desktop/salaries.csv";
BufferedReader br= new BufferedReader(new FileReader(csv));
String line;
Map<Integer, String> salaryMap = new TreeMap<Integer, String>();

try {
    br.readLine();
    while((line = br.readLine()) != null) {
        salaryMap.put(Integer.parseInt(line.split(",")[2]), line);
    }
} catch (IOException e) {
    e.printStackTrace();
}


try {
    FileWriter fw = new FileWriter("/home/user/Desktop/salaries.txt");
    BufferedWriter bw = new BufferedWriter(fw);
    List<String> list = new ArrayList<String>(salaryMap.values());
    for (String str : list) {
        bw.write(str);
        bw.newLine();
    }

    bw.flush();
    bw.close();

} catch (IOException e) {
    e.printStackTrace();
}
String csv=“/home/user/Desktop/salaries.csv”;
BufferedReader br=新的BufferedReader(新文件读取器(csv));
弦线;
Map salaryMap=newtreemap();
试一试{
br.readLine();
而((line=br.readLine())!=null){
salaryMap.put(Integer.parseInt(line.split(“,”[2]),line);
}
}捕获(IOE异常){
e、 printStackTrace();
}
试一试{
FileWriter fw=newfilewriter(“/home/user/Desktop/palaries.txt”);
BufferedWriter bw=新的BufferedWriter(fw);
List List=newarraylist(salaryMap.values());
for(字符串str:list){
bw.write(str);
换行符();
}
bw.flush();
bw.close();
}捕获(IOE异常){
e、 printStackTrace();
}

小心地图,put将覆盖您以前的值

可以使用Arrays.sort对本机数组进行排序,也可以使用guavas Iterables.sortedCopy

这里有一个Arrays.sort的代码库:

JavaNIO
  • Java提供了第二个I/O系统,称为NIO(新I/O)

  • NIO的开发目的是允许Java程序员实现高速I/O,而无需使用自定义本机代码。NIO将占用时间的I/O活动(如填充、释放缓冲区等)移回到操作系统中,从而大大提高了操作速度

    import java.io.File;
    
    import java.nio.charset.Charset;
    import java.nio.file.Files;
    import java.nio.file.Path;
    
    import java.util.List;
    
    //

    Path filePath = new File("csv_file_path").toPath();
    Charset charset = Charset.defaultCharset();        
    List<String> stringList = Files.readAllLines(filePath, charset);
    String[] stringArray = stringList.toArray(new String[]{});
    
    
    Arrays.sort(stringArray, new Comparator<String>(){
        public int compare(String first, String second) {
            return Integer.valueOf(first.split(",")[2]).compareTo(Integer.valueOf(second.split(",")[2]));
        }
    });
    
    for (String newstr: stringArray){
        System.out.println(newstr);
    }
    
    注:-必须为上述代码添加例外情况

  • defaultCharset():-(无参数)

    此方法返回此Java虚拟机的默认字符集

  • 公共静态列表readAllLines(路径,字符集cs):-

    参数(path-文件路径,cs-用于解码的字符集)

    此方法将文件中的所有行作为列表读取

现在,我使用toArray()方法将列表转换为数组,并实现了一个用于排序数组的比较器。
我已经重写了比较方法,比较了两个字符串,这两个字符串是每个句子中逗号(,)之后的第三个字符串,并将它们转换为数字,并按排序顺序排列。

您能写代码吗!!只是不明白。你应该自己试试,让我知道你遇到的问题。好的。在分类之前,我应该如何打印map的值?使用
TreeMap
而不是
HashMap
,这样它已经按照所需的顺序排序了,您只需对它进行迭代。@tomse但他可能需要自定义它,因为它将是对象的集合,而不仅仅是一个数据类型。您打算只写薪水吗?解释您的想法答:谢谢你的代码片段,它可能会提供一些即时的帮助。通过说明为什么这是一个很好的解决问题的方法,正确地解释它的教育价值,并将使它对未来有类似但不完全相同问题的读者更有用。请在回答中添加解释,并说明适用的限制和假设。
File file = new File("C:\\sandbox\\test.txt");
System.out.println(file.toPath());

Output:- C:\sandbox\test.txt