【问题标题】:Sort data in a text file in alphabetical order - Java按字母顺序对文本文件中的数据进行排序 - Java
【发布时间】:2018-05-20 20:32:25
【问题描述】:

我希望输出按字母顺序列出 userNameGenerator。我将 HashSet 转换为 ArrayList 因为集合无法排序,所以我将其更改为 ArrayList 以按字母顺序对列表进行排序。我使用 Collections.sort 按字母顺序对字符串列表进行排序,但是,输出仍然是 一样的。

我用于字母顺序的代码:

List sortedList = new ArrayList(personFile);
Collections.sort(sortedList); 
System.out.println();

输出:

Dompteuse -> Imran Sullivan,
Deservedness -> Eadie Jefferson,
Ostracize -> Eadie Jefferson,
Abattoir -> Angel Whitehouse,
Choreography -> Imran Sullivan,Taylor Vargas,Priya Oliver,
Goodfella -> Khalil Person,Eadie Jefferson,
Frolicwas -> Taylor Vargas,
DarknianIdeal -> Sophia Jeffery,Clyde Calderon,Taylor Vargas,Liyah Navarro,
Cremaster -> Aryan Hess,
Reliable -> Imran Sullivan,Aryan Hess,Angel Whitehouse,Priya Oliver,
Hootenany -> Clyde Calderon,
Acrimony -> Taylor Vargas,

完整代码:

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

public class Codes {
    public static void main(String[] args) { 
        List<Codes2> personFile = new ArrayList<>();

        try {   
            BufferedReader br = new BufferedReader(new FileReader("person-data.txt"));
            String fileRead = br.readLine();
            while (fileRead != null) {
                String[] personData = fileRead.split(":");                
                String personName = personData[0];
                String userNameGenerator = personData[1];                
                Codes2 personObj = new Codes2(personName, userNameGenerator);               
                personFile.add(personObj);
                fileRead = br.readLine();
            }
            br.close();
        }

        catch (FileNotFoundException ex) {            
            System.out.println("File not found!");
        } 

        catch (IOException ex) {             
            System.out.println("An error has occured: " + ex.getMessage());
        }

        Set<String> newStrSet = new HashSet<>();
        for(int i = 0; i < personFile.size(); i++){
            String[] regionSplit = personFile.get(i).getUserNameGenerator().split(", ");
            for(int j = 0; j < regionSplit.length; j++){
                newStrSet.add(regionSplit[j]);
            }
        }

        for (String s: newStrSet) {
            System.out.printf("%s -> ", s);
            for (Codes2 p: personFile) {
                if (p.getUserNameGenerator().contains(s)) {
                    System.out.printf("%s, ", p.getPersonName());
                }
            } 
            List sortedList = new ArrayList(personFile);
            Collections.sort(sortedList); 
            System.out.println();
        }       
    }
}

人物类:

public class Codes2 implements Comparable<Codes2> {
    private String personName;
    private String userNameGenerator;

    public Codes2(String personName, String userNameGenerator) {
        this.personName = personName;
        this.userNameGenerator = userNameGenerator;
    }

    public String getPersonName() {
        return personName;
    }

    public String getUserNameGenerator() {
        return userNameGenerator;
    }

    @Override
    public int compareTo(Codes2 o) {
        return getUserNameGenerator().compareTo(o.getUserNameGenerator());
    }

    public int compare(Object lOCR1, Object lOCR2) {                
        return ((Codes2)lOCR1).userNameGenerator                        
                .compareTo(((Codes2)lOCR2).userNameGenerator);            
    }
}

参考:Simple way to sort strings in the (case sensitive) alphabetical order

【问题讨论】:

  • 我认为您没有在任何地方打印排序列表是有原因的?
  • TreeSet 是自然排序的。
  • 您希望 Region 如何参与进来?那些也是排序的,还是你也只是按 userGeneratedName 和区域列出?
  • 为了以 Joe 的评论为基础,看起来您采用了一个正在使用 HashSets(但不是“工作”)的程序并试图将其转换为 ArrayList。但是您错过了一些细节,例如打印正确的输出。如果您没有一种长时间的方法来尝试做所有事情,这将更容易发现。将代码分解成更小的步骤(使用更小的方法),它会更容易阅读和调试。
  • 您的排序在您的用户名生成器的循环中。同样,您正在对 Code2 对象进行排序,而不是对存储在 newStrSet 中的用户名生成器进行排序。如果您使用 Java 8,则可以使用流式解决方案更简单。

标签: java


【解决方案1】:

正如@phatfingers 评论的那样,TreeSet 将尊重集合中条目的自然顺序。

由于 Codes2 已经实现了Comparable,您可以简单地将原来的 HashSet 替换为 TreeSet,然后收工。

请注意TreeSet documentation, 中的这一点:

请注意,由集合维护的顺序(无论是否显式 提供了比较器)必须与equals一致 正确实现 Set 接口。(参见 Comparable 或 Comparator 用于与等于一致的精确定义。)就是这样 因为 Set 接口是根据 equals 操作定义的, 但是 TreeSet 实例使用它的执行所有元素比较 compareTo(或比较)方法,因此两个元素被视为相等 通过这种方法,从集合的角度来看,它们是相等的。这 一个集合的行为是明确定义的,即使它的顺序是不一致的 等于;它只是不遵守集合的一般合同 界面。 (强调)

这意味着,虽然简单地使用 TreeSet 可能会单独工作,但您可能仍需要考虑在 Codes2 类中覆盖 equals() 和 hashCode(),以便排序行为与 equals 一致。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多