如何按字母顺序对文本文件进行排序?

时间:2011-02-11 15:33:11

标签: java sorting

例如,

我想要这些数据: -

     Manufacturer : - Violin

     Type : - Electric

     Colour: - Blue

     Price : $23



     Manufacturer : - Guitar

     Type : - Electric

     Colour: - Red

     Price : $54

看起来像: -

     Manufacturer : - Guitar

     Type : - Electric

     Colour: - Red

     Price : $54



     Manufacturer : - Violin

     Type : - Electric

     Colour: - Blue

     Price : $23

(请注意小提琴信息是如何低于吉他的,因为它按字母顺序排在“G”uitar之后。)

需要你的帮助尽快使用JAVA代码.....非常感谢你的帮助将受到高度赞赏。

5 个答案:

答案 0 :(得分:2)

解决这个问题的完整代码在这里的响应时间相对较长,但我可以给你一些指示:

首先创建一个类,其中包含有关每个对象“小提琴”,“吉他”等的信息。基本上,该类可能如下所示:

public class BlockOfText
{
   public String name;

   public String block;
}

,其中“name”是“Guitar”和“Violin”,“block”是整个块。 现在从输入文件中读取每个块并将它们保存在一个数组中。使块对象可排序(我认为在java中有类似于Comparable的东西)并对该块数组进行排序。现在将数组的每个条目写入文件。 :)

答案 1 :(得分:2)

您必须读取文件并将每个元素存储在数据结构中。

然后你只需定义比较方法即可。

有些事情:

class ReadFile { 
   ...
   void read(){
      List<Product> list = ...
      while( readAllLines() ) {
        if( line.startWith("*")){ 
         list.add( new Product( line ));
        }
      }
      Collections.sort( list );
  }
  ...
}

然后在Product

中定义比较方法
class Product implements Comparable<Product> { 
  public Product( String fromLine ) { 
     // take values ... 
  }
  // attributes 
 ...
 // etc. 
 And then 
 public int compareTo( Product other ) { 
    return this.name.compareTo( other.name );
 }
}

答案 2 :(得分:1)

您需要创建一个包含属性的类:

  • 制造商
  • 类型
  • 颜色
  • 价格

然后从文件中读取数据并使用数据创建一个Object,然后将每个对象添加到ArrayList,您可以在其中使用Collections.sort(...)方法。

您的课程可以实现Comparable接口,也可以使用BeanComparator。 Bean Comparator链接有一个实现Comparable的简单示例,创建自定义Comparator或使用BeanComparator,因此您不需要编写任何自定义代码。

答案 3 :(得分:1)

我的建议是逐行读取文件并创建“Item”类型的普通POJO(其中Item只是你自己编写的一个类,它有4个实例变量(所有字符串),即制造商,类型,颜色和价格)。

当您在文件中阅读时,您可以为文本文件中的每4行创建一个Item实例(即您的第一个Item将有manufacturer =“Violin”,type =“Electric”,color =“Blue”和price = “$ 23”)。

然后您可以在创建它们时将每个项目放到一个公共ArrayList上,一旦您读完该文件,就可以使用以下内容对其进行正确排序:

Collections.sort(itemList, new Comparator<Item>() {

   @Override
   public int compare(Item o1, Item o2) {
      return o1.getManufacturer().compareTo(o2);
   }
});

其中itemList是ArrayList<Item>

您的列表现在将进行排序,以便循环显示它,然后将每个项目中的数据写入您的ouptut文件,就这么简单。

编辑根据要求,我会提供更多详细信息,但是,虽然最初我说我会按照您的要求使用手动排序,但我不会再这样做了。相反,我会尝试向您解释Collections.sort方法,因为您知道如何使用它非常重要。

让我们开始使用Item类。我将公开这个类中的所有实例变量,尽管您可能宁愿将它们与通常的getter和setter方法一起私有(注意我也省略了package和import语句):

public class Item {
    public String manufacturer;        
    public String type;        
    public String colour;        
    public String price;

    public Item(String manufacturer, String type, String colour, String price) {
        this.manufacturer = manufacturer;
        this.type = type;
        this.colour = colour;
        this.price = price;
    }
}

此类将用于存储我们希望排序的数据。现在让我们来看看你的主要方法:

public static void main(String[] args) {
    try {
        BufferedReader reader = new BufferedReader(new FileReader("inputFile.txt"));
        String nextLine = reader.readLine();
        List<Item> listOfItems = new ArrayList<Item>();

        while (nextLine != null) {
            if (!nextLine.equals("\n") && !nextLine.isEmpty()) {
                String manufacturer = nextLine;
                String type = reader.readLine();
                String colour = reader.readLine();
                String price = reader.readLine();

                Item newItem = new Item(manufacturer, type, colour, price);
                listOfItems.add(newItem);
            }
            nextLine = reader.readLine();
        }
        reader.close();
        Collections.sort(listOfItems, new Comparator<Item>() {

            @Override
            public int compare(Item o1, Item o2) {
                return o1.manufacturer.compareTo(o2.manufacturer);
            }
        });            
        PrintWriter writer = new PrintWriter("outputFile.txt");

        for (Item item : listOfItems) {
            writer.println(item.manufacturer);
            writer.println(item.type);
            writer.println(item.colour);
            writer.println(item.price);
            writer.println();
        }
        writer.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

好的,重要的是要注意 Collections.sort 的工作原理。您将此方法传递给集合(或者更具体地说,在我们的示例中为List / ArrayList),它将为您对该列表中的条目进行排序。最大的问题是它如何知道哪个Item对象应该是第一个,第二个等等。由于我们想要对制造商进行排序,我们需要告诉sort()使用它们的制造商实例变量来比较Item对象。

这是sort()定义的第二个参数。这个new Comparator<Item>部分告诉它将对Item对象进行排序。 sort()将使用我们定义的compare()方法来进行此排序。它在排序过程中将项目相互比较,而compare()方法告诉sort()只是将正在排序的项目的制造商进行比较,并仅根据它进行排序。

如果您还不清楚某些事情,请具体询问我。我认为理解这个解决方案比向您展示如何编写冒泡排序更有益。如果你想要只是google“java bubble sort”,会弹出大量的文章/帖子。

答案 4 :(得分:0)

这一切都取决于您如何存储数据。如果您只是使用原始文本文件,则必须编写Java代码来解释数据,对其进行排序并吐出结果。或者,您可以尝试将数据加载到MySQL等数据库中,然后通过Java与它进行交互。

假设您可以以某种方式将数据加载到Java中,您可以执行以下操作:

public Instrument {
  public String manufacturer;
  public String type;
  public String color;
  public BigDecimal price;

  public Instrument(String manufacturer, String type, String color, BigDecimal price) {
    this.manufacturer = manufacturer;
    this.type = type;
    this.color = color;
    this.price = price;
  }

  public int compareTo(Object obj)
    Instrument temp = (Instrument)obj;

    return this.manufacturer.compareTo(temp.manufacturer);
  }
}

Instrument[] instruments = new Instrument[100]; // If you have 100 instruments in your file

instruments = LoadInstruments("INSRUMENTS.txt"); // Just an example of loading instruments

Arrays.sort(instruments);
相关问题