6

我正在使用 eclipse,我正在尝试对一个包含大约 40 行的文本文件进行排序,如下所示:

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

我想按第二个字段的字母顺序对它们进行排序,以便将文本文件更改为如下所示:

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

我相当确定我应该做一些涉及标记它们(我已经完成以显示它)和 BufferedWriter 的事情,但我一生都无法想出通过第二个或第三个字段来做到这一点的方法我觉得我错过了一些明显的东西。

4

7 回答 7

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?

于 2013-10-21T13:33:20.610 回答
4

你的比较器

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

你的排序

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

你的输出

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

如果您对此有任何疑问,请告诉我..

于 2013-10-21T13:45:59.950 回答
1

遵循@Tyler 的回答。您可以在 Movie 类中有一个默认实现,也可以通过调用Collections.sort(movieList, new MyComparator());来实现其他排序顺序。这里有一个两者的示例。

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

如果你想在你的集合上调用你自己的比较器:

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());
    }
}
于 2013-10-21T13:45:36.447 回答
1

您要做的是使用java.util.Comparatorand Collections.sort。可以找到更多信息:http: //docs.oracle.com/javase/7/docs/api/java/util/Comparator.html

于 2013-10-21T13:22:54.513 回答
1

String 类有一个非常有用的静态方法,称为“split”。您所做的就是调用 split 并将其放在分隔符中,它会返回一个带有拆分字符串的字符串数组。

这是一个例子:

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

上面的代码将打印以下内容:

How
Now
Brown
Cow

希望您可以使用它并使其适应您的问题。
祝你好运!

于 2013-10-21T13:23:04.330 回答
0

试试这样:--

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);
}
于 2013-10-21T13:39:31.263 回答
0

此解决方案使用 Java 8 API。

您实际上并不需要显式实现Comparator或创建Comparable类。使用Comparator.comparinglambda,我们可以通过自定义键优雅地对行进行排序。

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);
    }
}
于 2017-02-21T12:06:41.550 回答