开发者

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

开发者 https://www.devze.com 2023-02-05 04:31 出处:网络
I have written this code and don\'t know how to sort surnames in alphabetical order from my file to another 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) {
    开发者_C百科            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.

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. 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.
  2. Read ALL the data from file 1 into this List of objects.
  3. Create a class that implements Comparator with a generic specifying your POJO class
    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.
  4. Pass the list, and this Comparator implementation to Arrays.sort
  5. Write out your list of sorted java objects.

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. 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. No sense re-inventing the wheel when Java already has a good one ready for your use.


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

Add the compare() method available in the Collator instead of the equalsIgnoreCase(...) in the the sample code provided by RD01

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号