简体   繁体   中英

How to sort content of a csv file in java

I have a big csv file that looks like this

 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

I am able to display it but i don't know how to sort it and display it again sorted. Here's my code so far

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.");
            }
            }
    }
}

As you can see, i give the user the option to display the data, display them sorted (according to id) and i also want the user to choose how to sort the code. I am stuck at sorting.

  1. Stop reinventing the wheel; use a csv open source library (for example, opencsv).
  2. Create a class that represents one row of data in your csv file; I'll refer to this as RowClass .
  3. Read the CSV file one row at a time. Each row will arrive as a String[] .
  4. Create and populate one instance of RowClass per row of the CSV file.
  5. Store the RowClass objects in a List ; I'll call this rowList .
  6. Sort rowList using a Comparator that you create. Create one Comparator for each sort option.
  7. Implement RowClass.toString() to display one row.

This should help, I believe that you will figure out what's going on here

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;
        }

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM