Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Sorting text file lines

I'm using eclipse and I'm trying to sort a text file with about 40 lines that look like this:

1,Terminator,1984,Schwarzenegger
2,Avatar,2009,Worthington
3,Avengers,2012,Downey
4,Starwars,1977,Hammill
5,Alien,1979,Weaver

I want sort them alphabetically by the second field so that the text file is altered to look like this:

5,Alien,1979,Weaver
2,Avatar,2009,Worthington
3,Avengers,2012,Downey
4,Starwars,1977,Hammill
1,Terminator,1984,Schwarzenegger

I'm fairly certain I should be doing something involving tokenizing them (which I've already done to display it) and a BufferedWriter but I can't for the life of me think of a way to do it by the second or third field and I feel like I'm missing something obvious.

like image 346
Deoff Avatar asked Oct 21 '13 13:10

Deoff


1 Answers

You will first of course need to read a file, which you can learn how to do here.
Java: How to read a text file

This example will provide several ways you may write the file once you have sorted your data.
How do I create a file and write to it in Java?

As for sorting, I recommend creating a class Movie, which would look similar to

public class Movie implements Comparable<Movie> {  
    private String name;
    private String leadActor;
    private Date releaseDate;

    public Movie(String name, String leadActor, String releaseDate) {

    }

    @Override
    public int compareTo(Movie other) {

    }
}  

Ill leave it to you fill in the rest of the constructor and compareTo method. Once you have your compareTo method you will be able to call Collections.sort(List list) passing your list of Movie.

Here are some resources on implementing Comparable.
http://docs.oracle.com/javase/tutorial/collections/interfaces/order.html
Why should a Java class implement comparable?

like image 69
Tyler Avatar answered Sep 18 '22 01:09

Tyler