6

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.

Deoff
  • 77
  • 2
  • 3
  • 9

7 Answers7

6

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?

Community
  • 1
  • 1
Tyler
  • 827
  • 2
  • 11
  • 25
4

Your comparator

class SampleComparator implements Comparator<String> {
    @Override
    public int compare(String o1, String o2) {
           String array1[] = o1.split(",");
           String array2[] = o2.split(",");
           return array1[1].compareTo(array2[1]);
   }
}

Your Sorting

String [] lines= {"1,Terminator,1984,Schwarzenegger",
                       "2,Avatar,2009,Worthington",
                       "3,Avengers,2012,Downey",
                       "4,Starwars,1977,Hammill",
                       "5,Alien,1979,Weaver"};
List<String> rowList = new ArrayList<String>(Arrays.asList(lines));
Collections.sort(rowList, new SampleComparator());
for (String string : rowList) {
     System.out.println(string);
}   

Your Output

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

If you have any doubt on this let me know..

Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64
1

What you want to do is to use java.util.Comparator and Collections.sort. More on this can be found: http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html

Josh M
  • 11,611
  • 7
  • 39
  • 49
AppX
  • 528
  • 2
  • 12
1

The String class has a very helpful static method called "split". All you do is call split and put it in the delimiter and it gives back a String array with the split up string.

Here's an example:

String line = "How,Now,Brown,Cow";
String[] splitLine = line.split(",");
for(String l: splitLine)
{
    System.out.println(l);
}

The above code would print the following:

How
Now
Brown
Cow

Hopefully you can use this and adapt it to your problem.
Good luck!

Andrew Schuster
  • 3,229
  • 2
  • 21
  • 32
1

Following @Tyler answer. You can have a default implementation in the Movie class and additional sort orders that you can implement by calling Collections.sort(movieList, new MyComparator()); Here comes an example of both.

package com.stackoverflow;


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

    public Movie(String name, String leadActor, String releaseDate) {
        this.name = name;
        this.leadActor = leadActor;
        this.releaseDate = releaseDate;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLeadActor() {
        return leadActor;
    }

    public void setLeadActor(String leadActor) {
        this.leadActor = leadActor;
    }

    public String getReleaseDate() {
        return releaseDate;
    }

    public void setReleaseDate(String releaseDate) {
        this.releaseDate = releaseDate;
    }

    @Override

    public int compareTo(Movie other) {
        return getName().compareTo(other.getName());
    }
}

And if you want to make your own comparator called on your collection:

package com.stackoverflow;

import java.util.Comparator;

public class MyComparator  implements Comparator<Movie> {


    @Override
    public int compare(Movie o1, Movie o2) {
        return o1.getLeadActor().compareTo(o2.getLeadActor());
    }
}
AppX
  • 528
  • 2
  • 12
0

Try like this :--

ArrayList ar=new ArrayList();
String [] arr=new String[10];
int i=0;
try {
    Scanner sc=new Scanner(file);

    while (sc.hasNextLine()) 
    {
        String ss=sc.nextLine();
        i=i+1;
        arr[i]=ss;
    }
    ar.add(arr[5]);
    ar.add(arr[2]);
    ar.add(arr[3]);
    ar.add(arr[4]);
    ar.add(arr[1]);
    System.out.println(ar);
}
Hussain Shabbir
  • 14,801
  • 5
  • 40
  • 56
0

This solution uses Java 8 APIs.

You don't really need to have an explicit implementation of Comparator or create a Comparable class. Using Comparator.comparing with lambda we can elegantly sort lines by custom key.

import java.io.IOException;
import java.nio.file.*;
import java.util.Comparator;
import java.util.stream.Stream;

public class FileSortWithStreams {

    public static void main(String[] args) throws IOException {
        Path initialFile = Paths.get("files/initial.txt");
        Path sortedFile = Paths.get("files/sorted.txt");

        int sortingKeyIndex = 1;
        String separator = ",";

        Stream<CharSequence> sortedLines =
        Files.lines(initialFile)
             .map(s -> s.split(separator))
             .sorted(Comparator.comparing(s -> s[sortingKeyIndex]))
             .map(s -> String.join(separator, s));

        Files.write(sortedFile, sortedLines::iterator, StandardOpenOption.CREATE);
    }
}
diziaq
  • 6,881
  • 16
  • 54
  • 96