简体   繁体   English

如何使用Java在文件之间按字母顺序对姓氏进行排序?

[英]How do I use Java to sort surnames in alphabetical order from file to file?

I have written this code and don't know how to sort surnames in alphabetical order from my file to another file. 我已经编写了这段代码,不知道如何从文件到另一个文件按字母顺序对姓进行排序。

import java.io.*;
import java.util.*;

class Asmuo {
    String pavarde;
    String vardas;
    long buvLaikas;
    int atv1;
    int atv2;
    int atv3;
}

class Irasas {
    Asmuo duom;
    Irasas kitas;
}

class Sarasas {
    private Irasas p;

    Sarasas() {
        p = null;
    }

    Irasas itrauktiElementa(String pv, String v, long laikas, int d0, int d1,
            int d2) {
        String pvrd, vrd;
        int data0;
        int data1;
        int data2;
        long lks;
        lks = laikas;
        pvrd = pv;
        vrd = v;
        data0 = d0;

        data1 = d1;

        data2 = d2;
        Irasas r = new Irasas();
        r.duom = new Asmuo();
        uzpildymasDuomenimis(r, pvrd, vrd, lks, d0, d1, d2);
        r.kitas = p;
        p = r;
        return r;
    }

    void uzpildymasDuomenimis(Irasas r, String pv, String v, long laik, int d0,
            int d1, int d2) {
        r.duom.pavarde = pv;
        r.duom.vardas = v;
        r.duom.atv1 = d0;
        r.duom.buvLaikas = laik;
        r.duom.atv2 = d1;
        r.duom.atv3 = d2;
    }

    void spausdinti() {
        Irasas d = p;
        int i = 0;
        try {
            FileWriter fstream = new FileWriter("rez.txt");
            BufferedWriter rez = new BufferedWriter(fstream);
            while (d != null) {
                System.out.println(d.duom.pavarde + " " + d.duom.vardas + " "
                        + d.duom.buvLaikas + " " + d.duom.atv1 + " "
                        + d.duom.atv2 + " " + d.duom.atv3);
                rez.write(d.duom.pavarde + " " + d.duom.vardas + " "
                        + d.duom.buvLaikas + " " + d.duom.atv1 + " "
                        + d.duom.atv2 + " " + d.duom.atv3 + "\n");
                d = d.kitas;
                i++;
            }
            rez.close();
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        }

    }
}

public class Gyventojai {

    public static void main(String args[]) {
        Sarasas sar = new Sarasas();
        Calendar atv = Calendar.getInstance();
        Calendar isv = Calendar.getInstance();

        try {
            FileInputStream fstream = new FileInputStream("duom.txt");
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String eil;
            while ((eil = br.readLine()) != null) {
                String[] cells = eil.split(" ");
                String pvrd = cells[0];
                String vrd = cells[1];
                atv.set(Integer.parseInt(cells[2]), Integer.parseInt(cells[3]),
                        Integer.parseInt(cells[4]));
                isv.set(Integer.parseInt(cells[5]), Integer.parseInt(cells[6]),
                        Integer.parseInt(cells[7]));
                long laik = (isv.getTimeInMillis() - atv.getTimeInMillis())
                        / (24 * 60 * 60 * 1000);
                int d0 = Integer.parseInt(cells[2]);
                int d1 = Integer.parseInt(cells[3]);
                int d2 = Integer.parseInt(cells[4]);
                sar.itrauktiElementa(pvrd, vrd, laik, d0, d1, d2);

            }
            in.close();
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        }

        sar.spausdinti();

    }
}

You'll have to forgive me if I make some incorrect assumptions, as I don't speak Lithuanian?? 如果我做一些错误的假设,您将不得不原谅我,因为我不会讲立陶宛语? so your variable and method names make it difficult for me to comprehend your code. 因此,您的变量名和方法名使我很难理解您的代码。

It looks like you have your own Linked List structure of 'Person' records. 看来您具有自己的“人员”记录的链接列表结构。 There are a few different ways to sort your records based on surname. 有几种不同的方法可以根据姓氏对记录进行排序。 One way would be to write a method to sort your linked list by manually moving nodes and breaking/recreating the links between your nodes. 一种方法是编写一种方法,通过手动移动节点并断开/重新创建节点之间的链接来对链接列表进行排序。

Another way is to dump your list into a standard list, and sort the list using Collections.sort() and an appropriate Comparator class. 另一种方法是将列表转储到标准列表中,然后使用Collections.sort()和适当的Comparator类对列表进行排序。

class Sarasas {
...
private List<Asmuo> sortList() {
    // dump your list into an ArrayList
    List<Asmuo> data = new ArrayList<Asmuo>();
    Irasas node = p;   // start with the Sarasas object's head node
    while (node != null) {
        data.add(node);
        node = node.kitas;
    }

    // sort your list
    Collections.sort(data, new AsmuoComparator() );

    return data;
}


class AsmuoComparator  implements Comparator<Asmuo>
{
    public int compare(Asmuo p1, Asmuo p2)
    {
        return p1.pavarde.compareToIgnoreCase(p2.pavarde);  
            // I'm assuming pavarde is the surname?
    }
}

Now you can use the List that is returned for whatever you need. 现在,您可以根据需要使用返回的列表。 To iterate through the list in order and do something to each item: 要依次遍历列表并对每个项目执行以下操作:

List<Asmuo> data = sortList();
for (Asmuo a : data) {
    // write to file, etc...
}

Good luck! 祝好运! and let me know if any of my assumptions are wrong, so I can modify my answer. 并让我知道我的假设是否有误,因此我可以修改答案。

While I don't have a specific comment about this code, because frankly, I find it very difficult to read given my lack of understanding of the language you're using, as a general approach, this is how I would solve the problem you're asking: 虽然我对此代码没有具体评论,但是坦率地说,由于我对您所使用的语言缺乏理解,因此我很难阅读,作为一种通用方法,这就是我如何解决您的问题在问:

  1. Create a List type to hold the list of names/data/etc using a POJO class to hold the data. 使用POJO类创建列表类型以保存名称/数据/等列表,以保存数据。 I frequently use the LinkedList type if I don't know the length of the list before hand, or ArrayList if I know how many elements in advance. 如果我事先不知道列表的长度,那么我经常使用LinkedList类型;如果我事先知道多少个元素,我经常使用ArrayList类型。
  2. Read ALL the data from file 1 into this List of objects. 将文件1中的所有数据读入该对象列表。
  3. Create a class that implements Comparator with a generic specifying your POJO class 创建一个类,该类使用指定POJO类的泛型来实现Comparator
    This class is where you do the comparison of names to check the order. 在该类中,您可以进行名称比较以检查顺序。 You can also use the java String method compare or compareIgnoreCase to have java do the name comparison for you. 您还可以使用java String方法compare或compareIgnoreCase来让java为您进行名称比较。
  4. Pass the list, and this Comparator implementation to Arrays.sort 将列表以及此Comparator实现传递给Arrays.sort
  5. Write out your list of sorted java objects. 写出已排序的Java对象列表。

This works for any java object type incidentally, and the sorting method can be entirely arbitrary, or based on some novel characteristic of the data. 顺便说一下,这适用于任何Java对象类型,并且排序方法可以完全是任意的,也可以基于数据的某些新颖特征。 I use this kind of methodology not infrequently, and as Java does most of the heavy lifting for you, it minimizes your investment of time and effort. 我很少使用这种方法,并且由于Java为您完成了大部分繁重的工作,因此它可以最大程度地减少您的时间和精力投入。 No sense re-inventing the wheel when Java already has a good one ready for your use. 当Java已经准备好使用时,重新发明轮子就毫无意义。

I am surprised that none of the answers have suggested the use of Collator in this case. 令我惊讶的是,没有答案表明在这种情况下应使用整理器 So I just want to add that you should be using Collator for comparision as shown below 所以我只想补充一下,您应该使用整理器进行比较,如下所示

Collator collator = Collator.getInstance(new Locale(...));
Collections.sort(yourList, collator);

Complete example can be found here 完整的例子可以在这里找到


Edited with a hint to be used in RD01's code 编辑并带有要在RD01的代码中使用的提示

Add the compare() method available in the Collator instead of the equalsIgnoreCase(...) in the the sample code provided by RD01 RD01提供的示例代码添加的分页器,而不是equalsIgnoreCase可用的compare()方法(...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何按字母顺序对文件进行排序? - How to sort a file in alphabetical order? 按字母顺序对文本文件中的数据进行排序-Java - Sort data in a text file in alphabetical order - Java JAVA:如何按字母顺序对从文件读取并输出到控制台的字符串进行排序? - JAVA: How to sort strings read from file and output to console in alphabetical order? 使用方法(Java)按字母顺序将文件内容排序到新文件中 - Sort contents of file in alphabetical order into a new file using methods (Java) 如何在Java中按频率然后按字母顺序对字符串排序? - How do I order a string by frequency and then by alphabetical order in java? 如何使用比较器和集合以不同方式对文本文件进行排序? (Java)? - How Can I Use Comparators and Collections In Order To Sort A Text File In Different Ways? (Java)? 如何使用 Java 中的 actionlistener 按字母顺序对联系人列表进行排序? - How do you sort a contact list in alphabetical order using actionlistener in Java? 如何按字母顺序File.listFiles? - how to File.listFiles in alphabetical order? 如何按字母顺序对列表视图进行排序 - How to sort a listview in alphabetical order 如何按字母顺序对ArrayList排序并与setText方法一起使用? - How do I sort my ArrayList in alphabetical order and have it used with a setText method?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM