简体   繁体   中英

How to sort file using Arraylist according to specific token?

I have a file that has some info about ticket issuance which looks like that.

Test Passenger  Aegean      Business    06:00   Athens-London   650.92  E1  T9759   09/06/2021 12:45:22
Test Passenger  RyanAir     Economy     10:30   Athens-London   200.65  E2  T9946   09/06/2021 12:45:30
Test Passenger  Lufthansa   Business    12:30   Athens-London   700.50  E3  T8189   09/06/2021 12:45:37

The attributes are passengerName , Company , ticketClass , departureTime , itenerary , ticketCost , gate , ticketId , issueDate which are seperated using "\t" as the delimiter . Every input in the file is a String . The file gets loaded in an Arraylist from where I try to sort it according to the price of the ticket. What I do is I split the arraylist in tokens in order to get the correct thing to compare from each arraylist, but it doesn't seem to work. Also I have tried to implement all the Collections.sort() examples that I found but still nothing works. The desired result to get the file sorted so I can display it in a JTextArea .Every field of the file is a String which is an attribute of the Ticket class and the ArrayList is of type Ticket ( ArrayList<Ticket> = new ArrayList(); ). Here is what I have till now.

private void loadFromFile(String fileName) {
     
    ArrayList<Ticket> ticketsList = new ArrayList();

    try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
        
        String line = "";
        String[] tokens;
        Ticket ticket = new Ticket();
        
        float totalTicketCost = (float) 0.00;
        int numberOfLines = 0;

        while(reader.ready()){
            line = reader.readLine();

            tokens = line.split("\t");

            if (tokens.length == 9) {

                ticket = new Ticket(tokens[0], tokens[1], tokens[2], tokens[3], tokens[4], tokens[5],tokens[6], tokens[7], tokens[8]);
                ticketsList.add(ticket);
            }

            area.append(ticket.toString());

            totalTicketCost += Float.parseFloat(tokens[5]);
                
            // format dacimals for total cost
            DecimalFormat df = new DecimalFormat();
            df.setMaximumFractionDigits(2);

            numberOfTickets.setText(String.valueOf(numberOfLines));
            totalCost.setText(String.valueOf(df.format(totalTicketCost)));

            numberOfLines++; //Total number of tickets
            
        }
        
        // Since nothing works let's try the C way of finding the the biggest ticketCost
        float tmp = Float.valueOf(ticketsList.get(0).getTicketPrice());
        float max = Float.valueOf(ticketsList.get(0).getTicketPrice());
          
        for( int i = 0; i < ticketsList.size(); i++){
            
            tmp = Float.valueOf(ticketsList.get(i).getTicketPrice());
            
            if( max < tmp ){
                max = tmp;
               // currentBig = Float.valueOf(ticketsList.get(i+1).getTicketPrice());
            }    
            System.out.println(tmp + "\n");
        }
        
    } catch (Exception e) {
    }
}  

You can sort objects in a list with the sort method ( https://docs.oracle.com/javase/8/docs/api/java/util/List.html#sort-java.util.Comparator- ). To compare them you can use the 'Comparator' class ( https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html ):

// add tickets to list (as received from file)
List<Ticket> dummies = getTickets();

dummies.sort(Comparator.comparing(Ticket::getName));

// you now have a sorted list that can be printed/displayed
for(Ticket t : dummies)
    printTicket(t);

You simply need a getter for the corresponding token (ie member variable) you want the list to be sorted by. To sort by price simply use dummies.sort(Comparator.comparing(Ticket::getPrice)); (assuming price is an int for example). Output (sorted by name):

0   A-ticket    Economy 
2   B-ticket    Economy 
4   C-ticket    Business    
3   C-ticket    Business    
1   D-ticket    Business

The first number represents the order in which the ticket was added to the list (eg A-ticket was added first and D-ticket second). Please note that you can also sort by multiple tokens with this method by adding .thenComparing(Ticket::getId) so if two tickets have the same name, they can be sorted by id. Adding this the sorting line becomes:

dummies.sort(
           Comparator.comparing(Ticket::getName)
                    .thenComparing(Ticket::getId)
    );

and the output:

0   A-ticket    Economy 
2   B-ticket    Economy 
3   C-ticket    Business    
4   C-ticket    Business    
1   D-ticket    Business

(notice how the two C-tickets have changed 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