CSV文件转换为ArrayList,根据两个不同的列进行排序,然后打印出结果。

huangapple 未分类评论44阅读模式
英文:

CSV file to ArrayList, Sorting it by 2 different columns, and printing it

问题

我有一个CSV文件,每一行的格式为:20个字符的字符串,10个字符的字符串,4个字符的字符串和一个双精度数。

目标是读取该文件并将信息存储到一个列表集合中。

然后使用一个比较器对第3列和第1列进行排序。

我想知道如何对它们进行排序,以及是否有更简单的方法来做到这一点。理想情况下,打印输出将会以以下方式分隔开:

System.out.printf("%-20s%-10s%-4s%10s%n", Result.get(0), Result.get(1), Result.get(2), Result.get(3));

我尝试过这样做,但是不能在不需要"System.out.println(CSVtoArrayList(Line));"这一行的情况下显示。以下是我当前的代码:

public static void main(String[] args) {
    BufferedReader Buffer = null;
    
    try {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter file name: ");
        String input1 = scanner.nextLine();
        String Line;
        Buffer = new BufferedReader(new FileReader(input1));
        
        while ((Line = Buffer.readLine()) != null) {
            System.out.println(CSVtoArrayList(Line));
        }
        
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (Buffer != null) Buffer.close();
        } catch (IOException Exception) {
            Exception.printStackTrace();
        }
    }
}

public static ArrayList<String> CSVtoArrayList(String CSV) {
    ArrayList<String> Result = new ArrayList<String>();
    
    if (CSV != null) {
        String[] splitData = CSV.split("\\s*,\\s*");
        for (int i = 0; i < splitData.length; i++) {
            if (!(splitData[i] == null) || !(splitData[i].length() == 0)) {
                Result.add(splitData[i].trim());
            }
        }
    }
    
    return Result;
}

当前代码的输出类似于:

Enter file name:
comma.txt
[frist movei, Bob, 1999, 24.98]
[first mobie, Steve, 1999, -345.67]
[first movie, Pam, 1999, 0.00]
[other moive, Sam, 1562, -42.16]
[something, Sue, 8951, 224.62]
英文:

I have a CSV file each line formatted as: 20 char string, 10 char string, 4 char string, and a double.

The goal is to read the file and store the information into a list collection.

then sort using a comparator on the 3rd column and then the 1st column.

What I'd like to know is how to sort them, and whether or not there is an easier way of doing this. ideally the print would be spaced out with something like

System.out.printf(&quot;%-20s%-10s%-4s%10s%n&quot;, Result.get(0), Result.get(1), Result.get(2), Result.get(3));

Which I attempted, but could not display without needing the "System.out.println(CSVtoArrayList(Line));" line. my current code:

public static void main(String[] args) {
	
	BufferedReader Buffer = null;
	
	try {
		Scanner scanner = new Scanner(System.in);
		System.out.println(&quot;Enter file name: &quot;);
		String input1 = scanner.nextLine(); 
		String Line;
		Buffer = new BufferedReader(new FileReader(input1));
		
		while ((Line = Buffer.readLine()) != null) {
			System.out.println(CSVtoArrayList(Line));

			}
		
	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		try {
			if (Buffer != null) Buffer.close();
		} catch (IOException Exception) {
			Exception.printStackTrace();
		}
	}
}


public static ArrayList&lt;String&gt; CSVtoArrayList(String CSV) {
	ArrayList&lt;String&gt; Result = new ArrayList&lt;String&gt;();
	
	if (CSV != null) {
		String[] splitData = CSV.split(&quot;\\s*,\\s*&quot;);
		for (int i = 0; i &lt; splitData.length; i++) {
			if (!(splitData[i] == null) || !(splitData[i].length() == 0)) {
				Result.add(splitData[i].trim());

			}
		}
	}
	
	return Result;
	
}

this currently prints out something like:

Enter file name: 
comma.txt
[frist movei, Bob, 1999, 24.98]
[first mobie, Steve, 1999, -345.67]
[first movie, Pam, 1999, 0.00]
[other moive, Sam, 1562, -42.16]
[something, Sue, 8951, 224.62]

答案1

得分: 0

private static final String COLUMN_SEPARATOR = ",";

public static void main(String[] args) throws Exception
{
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter file name:");
    String input1 = scanner.nextLine();
    String csvFile = input1;
    InputStream inputStream = new FileInputStream(input1);
    List<List<String>> lines = readCsv(inputStream);
    Comparator<List<String>> c2 = createAscendingComparator(2);
    Comparator<List<String>> c0 = createAscendingComparator(0);
    Comparator<List<String>> comparator = createComparator(c2, c0);
    Collections.sort(lines, comparator);
    printCsv(lines);
}

private static List<List<String>> readCsv(InputStream inputStream) throws IOException
{
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    List<List<String>> lines = new ArrayList<List<String>>();

    String line = null;

    while (true)
    {
        line = reader.readLine();
        if (line == null)
        {
            break;
        }
        List<String> list = Arrays.asList(line.split(COLUMN_SEPARATOR));
        lines.add(list);
    }
    return lines;
}

private static void printCsv(List<List<String>> lines) throws IOException
{
    for (List<String> list : lines)
    {
        System.out.printf("%-20s%-10s%-4s%10s%n", list.get(0), list.get(1), list.get(2), list.get(3));
    }
}

private static <T> Comparator<T> createComparator(Comparator<? super T>... delegates)
{
    return (t0, t1) ->
    {
        for (Comparator<? super T> delegate : delegates)
        {
            int n = delegate.compare(t0, t1);
            if (n != 0)
            {
                return n;
            }
        }
        return 0;
    };
}

private static <T extends Comparable<? super T>> Comparator<List<T>> createAscendingComparator(int index)
{
    return createListAtIndexComparator(Comparator.naturalOrder(), index);
}

private static <T extends Comparable<? super T>> Comparator<List<T>> createAscendingComparator1(int index)
{
    return createListAtIndexComparator(Comparator.naturalOrder(), index);
}

private static <T> Comparator<List<T>> createListAtIndexComparator(Comparator<? super T> delegate, int index)
{
    return (list0, list1) ->
        delegate.compare(list0.get(index), list1.get(index));
}
英文:

i started from scratch, and using code i found:

https://stackoverflow.com/questions/26448813/how-to-sort-csv-file-by-two-columns-in-java

i achieved the required results

private static final String COLUMN_SEPARATOR = &quot;,&quot;;

public static void main(String[] args) throws Exception
{
	Scanner scanner = new Scanner(System.in);
	System.out.println(&quot;Enter file name: &quot;);
    String input1 = scanner.nextLine(); 
    String csvFile = input1;
    InputStream inputStream = new FileInputStream(input1);
    List&lt;List&lt;String&gt;&gt; lines = readCsv(inputStream);
    Comparator&lt;List&lt;String&gt;&gt; c2 = createAscendingComparator(2);
    Comparator&lt;List&lt;String&gt;&gt; c0 = createAscendingComparator(0);
    Comparator&lt;List&lt;String&gt;&gt; comparator = createComparator(c2, c0);
    Collections.sort(lines, comparator);
    printCsv(lines);        
}

private static List&lt;List&lt;String&gt;&gt; readCsv(
    InputStream inputStream) throws IOException
{
    BufferedReader reader = new BufferedReader(
        new InputStreamReader(inputStream));
    List&lt;List&lt;String&gt;&gt; lines = new ArrayList&lt;List&lt;String&gt;&gt;();

    String line = null;

    while (true)
    {
        line = reader.readLine();
        if (line == null)
        {
            break;
        }
        List&lt;String&gt; list = Arrays.asList(line.split(COLUMN_SEPARATOR));
        lines.add(list);
    }
    return lines;
}

private static void printCsv(List&lt;List&lt;String&gt;&gt; lines) 
    throws IOException
{

    for (List&lt;String&gt; list : lines)
    {
    	System.out.printf(&quot;%-20s%-10s%-4s%10s%n&quot;, list.get(0),list.get(1),list.get(2), list.get(3));
    
    }

}

private static &lt;T&gt; Comparator&lt;T&gt;
    createComparator(Comparator&lt;? super T&gt;... delegates)
{
    return (t0, t1) -&gt; 
    {
        for (Comparator&lt;? super T&gt; delegate : delegates)
        {
            int n = delegate.compare(t0, t1);
            if (n != 0)
            {
                return n;
            }
        }
        return 0;
    };
}

private static &lt;T extends Comparable&lt;? super T&gt;&gt; Comparator&lt;List&lt;T&gt;&gt;
    createAscendingComparator(int index)
{
    return createListAtIndexComparator(Comparator.naturalOrder(), index);
}

private static &lt;T extends Comparable&lt;? super T&gt;&gt; Comparator&lt;List&lt;T&gt;&gt;
    createAscendingComparator1(int index)
{
    return createListAtIndexComparator(Comparator.naturalOrder(), index);
}

private static &lt;T&gt; Comparator&lt;List&lt;T&gt;&gt;
    createListAtIndexComparator(Comparator&lt;? super T&gt; delegate, int index)
{
    return (list0, list1) -&gt; 
        delegate.compare(list0.get(index), list1.get(index));
}

huangapple
  • 本文由 发表于 2020年4月8日 09:12:23
  • 转载请务必保留本文链接:https://java.coder-hub.com/61091832.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定