如何按频率对字符串进行排序,然后按第一次出现

时间:2017-05-16 12:36:07

标签: java

你好也许这个问题已在其他地方得到解答,但我能找到它。 我有包含

的文本文件

“此文字很短,文字很短。”

输出应为

1

1和

2是

2短

2 text

在我的代码中没有字母顺序它只是打印:

1和

1

2短

2是

2 text

我的代码是

public static void main(String[] args) throws IOException {

    Scanner sc = new Scanner(new File("file.txt"));
    List<String> lines = new ArrayList<String>();
    while (sc.hasNextLine()){
        lines.add(sc.nextLine());
    }

    String[] arr = lines.toArray(new String[0]);
    String text = Arrays.toString(arr);
    String test = text.replaceAll("\\p{P}","");

    List<String> list = Arrays.asList(test.split(" ")); 
    Set<String> uniq = new HashSet<String>(list);
    for (String w : uniq){
        System.out.printf("%n%d     %s",Collections.frequency(list, w), w);

    }
}

任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:0)

试试这个

  public static void main(String[] args) throws IOException {

    Scanner sc = new Scanner(new File("file.txt"));
    List<String> lines = new ArrayList<String>();
    while (sc.hasNextLine()){
        lines.add(sc.nextLine());
    }


    String[] arr = lines.toArray(new String[0]);
    String text = Arrays.toString(arr);
    String test = text.replaceAll("\\p{P}","");

    List<String> list = Arrays.asList(test.split(" ")); 
    SortedSet<String> uniq = new TreeSet<String>(list);


    for (String w : uniq){
        System.out.printf("%n%d     %s",Collections.frequency(list, w), w);

    }
}

答案 1 :(得分:0)

您实际要求的是有序的哈希集。 这是一个类似的问题:ordering a hashset example?

您需要做的就是在for循环之前添加一行

Set<String> uniqTree = new TreeSet<String>(uniq);

然后你可以通过执行以下操作迭代uniq中的元素:

for(String w : uniqTree){ 
    // print out the string
}

hashset没有任何保证的排序,而hashtree将通过传递给treeset的构造函数的Comparator或者&#34; natural&#34;对传递给它的元素的排序。在你的情况下,hashset的元素,即字符串已经实现了Comparable接口(即你可以使用compareTo()),这就是你可以将hashset传递给treeset的原因。

参考文献: https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html https://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html

相关问题