如何在java中对csv文件的内容进行排序

时间:2017-12-06 16:03:04

标签: java csv sorting

我有一个看起来像这样的大csv文件

 Order ID,Order Priority,Order Quantity,Unit Price,Ship Mode,Customer Name,Customer Segment,Product Category
 3,Low,6,38.94,Regular Air,Muhammed MacIntyre,Small Business,Office Supplies
 293,High,49,208.16,Delivery Truck,Barry French,Consumer,Office Supplies
 293,High,27,8.69,Regular Air,Barry French,Consumer,Office Supplies
 483,High,30,195.99,Regular Air,Clay Rozendal,Corporate,Technology

我可以显示它,但我不知道如何对它进行排序并再次显示它排序。到目前为止,这是我的代码

package project1;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;

public class Test {
    public static void main(String[] args) throws FileNotFoundException {
            Scanner input = new Scanner(System.in);
            int choice=0;
            boolean flag = true;

            while (flag) {
                System.out.println("Enter 1 to display data.");
                System.out.println("Enter 2 to sort data.");
                System.out.println("Enter 3 to idk.");
                System.out.println("Enter 0 to exit.");
                System.out.print("Your choice: ");
                choice = input.nextInt(); 
                if (choice ==1) {
                    File inputFile = new File("dataToLoad.csv");
                    String line;
                    String delimiter = ",";
                    Scanner in = new Scanner(inputFile);
                    int numberOfLines = 0;
                    int numberOfColumns = 0;
                    while (in.hasNextLine()){
                        line = in.nextLine();
                        numberOfLines++;
                    }
                    in.close();
                    String[][] data = new String[numberOfLines][8];
                    in = new Scanner(inputFile);
                    int currentRow = 0;
                    while (in.hasNextLine()){
                        line = in.nextLine();
                        String[] parts = line.split(delimiter);
                        numberOfColumns = parts.length;
                        for (int i = 0; i<numberOfColumns; i++) {
                            data[currentRow][i] = parts[i];
                        }
                        currentRow++;
                    }
                    in.close();
                    System.out.println(Arrays.deepToString(data));
                    for (int row=0; row<numberOfLines; row++) {
                        for (int col=0; col<numberOfColumns; col++) {
                            System.out.printf("%-20s", data[row][col]);
                        }
                        System.out.println();
                    }
                }
                else {
                    if (choice ==2) {

                    }
                    else 
                        if (choice==0) {
                        System.out.println("Good bye!");
                        flag = false;
                    }
                else System.out.println("I am sorry, this is not a valid option. Please try again.");
            }
            }
    }
}

正如您所看到的,我为用户提供了显示数据的选项,显示它们的排序(根据id),我还希望用户选择如何对代码进行排序。我被困在排序。

2 个答案:

答案 0 :(得分:2)

  1. 停止重新发明轮子;使用csv开源库(例如,opencsv)。
  2. 创建一个表示csv文件中一行数据的类;我将此称为RowClass
  3. 一次读取一行CSV文件。每行将以String[]
  4. 的形式到达
  5. 创建并填充CSV文件每行RowClass的一个实例。
  6. RowClass个对象存储在List;我将此称为rowList
  7. 使用您创建的rowListComparator进行排序。为每个排序选项创建一个Comparator
  8. 实施RowClass.toString()以显示一行。

答案 1 :(得分:0)

这应该有所帮助,我相信你会弄清楚这里发生了什么

<强> Main.java

package pkg;

import java.util.Arrays;

import static pkg.Order.OrderBuilder;

public class Main {

    private static Order[] orders = new Order[3];
    private static OrderBuilder orderBuilder = new OrderBuilder();

    public static void main(String[] args) {
        Order order1 = orderBuilder.createNewOrder().withId(10).withCustomerName("John").withPrice(1.23f).withPriority("high").build();
        Order order2 = orderBuilder.createNewOrder().withId(20).withCustomerName("Lee").withQuantity(3.4f).build();
        Order order3 = orderBuilder.createNewOrder().withId(30).withCustomerName("Someone").withPriority("low").build();

        orders[0] = order3;
        orders[1] = order1;
        orders[2] = order2;

        System.out.println("Before sorting");
        for(int i = 0; i < orders.length; i++) {
            System.out.println(orders[i].getId());
        }

        Arrays.sort(orders);

        System.out.println("After sorting");
        for(int i = 0; i < orders.length; i++) {
            System.out.println(orders[i].getId());
        }
    }
}

<强> Order.java

package pkg;

public class Order implements Comparable<Order> {
    private int id;
    private String priority;
    private float quantity;
    private float price;
    private String shipMode;
    private String customerName;
    private String customerSegment;
    private String productCategory;

    private void setId(int id) {
        this.id = id;
    }

    int getId() {
        return this.id;
    }

    private void setPriority(String priority) {
        this.priority = priority;
    }

    private void setQuantity(float quantity) {
        this.quantity = quantity;
    }

    private void setPrice(float price) {
        this.price = price;
    }

    private void setShipMode(String shipMode) {
        this.shipMode = shipMode;
    }

    private void setCustomerName(String customerName) {
        this.customerName = customerName;
    }

    private void setCustomerSegment(String customerSegment) {
        this.customerSegment = customerSegment;
    }

    private void setProductCategory(String productCategory) {
        this.productCategory = productCategory;
    }

    @Override
    public int compareTo(Order o) {
        return this.id - o.getId();
    }

    static class OrderBuilder {
        private Order order;

        OrderBuilder withId(int id) {
            order.setId(id);
            return this;
        }

        OrderBuilder withPriority(String priority) {
            order.setPriority(priority);
            return this;
        }

        OrderBuilder withQuantity(float quantity) {
            order.setQuantity(quantity);
            return this;
        }

        OrderBuilder withPrice(float price) {
            order.setPrice(price);
            return this;
        }

        OrderBuilder withShipMode(String shipMode) {
            order.setShipMode(shipMode);
            return this;
        }

        OrderBuilder withCustomerName(String customerName) {
            order.setCustomerName(customerName);
            return this;
        }

        OrderBuilder withCustomerSegment(String customerSegment) {
            order.setCustomerSegment(customerSegment);
            return this;
        }

        OrderBuilder withProductCategory(String productCategory) {
            order.setProductCategory(productCategory);
            return this;
        }

        OrderBuilder createNewOrder() {
            order = new Order();
            return this;
        }

        Order build() {
            return order;
        }

    }
}