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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With