简体   繁体   English

按字母顺序对文本文件中的数据进行排序-Java

[英]Sort data in a text file in alphabetical order - Java

I want the output to list the userNameGenerator in alphabetical order. 我希望输出按字母顺序列出userNameGenerator。 I converted the HashSet into an ArrayList because sets cannot be sorted, so I changed it to an ArrayList to sort out the list in alphabetical order. 我将HashSet转换为ArrayList,因为无法对集合进行排序,因此我将其更改为ArrayList以按字母顺序对列表进行排序。 I used Collections.sort to sort the list of strings in alphabetical order, however, the output is still the same. 我使用Collections.sort来按字母顺序对字符串列表进行排序,但是输出仍然相同。

Code I used for alphabetical order: 我用于字母顺序的代码:

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

Output: 输出:

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,

Full Code: 完整代码:

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

Person Class: 人员类别:

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

Reference: Simple way to sort strings in the (case sensitive) alphabetical order 参考: 以(区分大小写)字母顺序对字符串排序的简单方法

As @phatfingers commented, a TreeSet will respect the natural order of the entries in the set. 正如@phatfingers所说,TreeSet将尊重集合中条目的自然顺序。

Since Codes2 already implements Comparable , you could simply replace your original HashSet with a TreeSet and call it a day. 由于Codes2已经实现了Comparable ,因此您可以简单地用TreeSet替换原始的HashSet并将其命名为day。

Note this from the TreeSet documentation, however: 但是,请从TreeSet文档中注意这一点:

Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals if it is to correctly implement the Set interface. 请注意, 如果要 正确实现Set接口,则由集合(无论是否提供显式比较器)维护的顺序必须等于equals (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal. (有关与equals一致的精确定义,请参见Comparable或Comparator。)之所以这样,是因为Set接口是根据equals操作定义的,但是TreeSet实例使用其compareTo(或compare)方法执行所有元素比较,因此两个从集合的角度来看,此方法认为相等的元素是相等的。 The behavior of a set is well-defined even if its ordering is inconsistent with equals; 即使集合的顺序与equals不一致,它的行为也是明确定义的; it just fails to obey the general contract of the Set interface. 它只是不遵守Set接口的一般约定。 (emphasis added) (添加了重点)

What this means is that, while simply using a TreeSet probably work by itself, you may still want to consider overriding equals() and hashCode() in your Codes2 class so that the ordering behavior is consistent with equals. 这意味着,尽管仅使用TreeSet可能本身即可工作,但您可能仍要考虑在Codes2类中重写equals()和hashCode(),以便排序行为与equals保持一致。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM