如何按值对TreeSet进行排序?

问题描述 投票:1回答:3

我是TreeMapTreeSet以及喜欢的新手,并且想知道如何按值对数据结构进行排序?我意识到使用TreeSet你可以自动将它按字母顺序排序,但我希望它通过值来订购?有关如何做到这一点的任何想法?

它目前打印像......

  • aaa:29
  • aaahealthart:30
  • 来自:23
  • 修道院:14
  • 腹部:3
  • 阿伯丁:29
  • 阿伯丁大学:20

当我想要它打印像......

  • aaahealthart:30
  • aaa:29
  • 阿伯丁:29
  • 来自:23
  • 阿伯丁大学:20
  • 修道院:14
  • 腹部:3

这是我的方法......

ArrayList<String> fullBagOfWords = new ArrayList<String>();
public Map<String, Integer> frequencyOne;

public void termFrequency() throws FileNotFoundException{
    Collections.sort(fullBagOfWords);
    Set<String> unique = new TreeSet<String>(fullBagOfWords);
    PrintWriter pw = new PrintWriter(new FileOutputStream(frequencyFile));
    pw.println("Words in Tweets :   Frequency of Words");
    for (String key : unique) {
        int frequency = Collections.frequency(fullBagOfWords, key);

        System.out.println(key + ": " + frequency);
        pw.println(key + ": " + frequency);
        }
    pw.close();
    }

感谢所有帮助人员。

java sorting treemap treeset
3个回答
2
投票

按密钥命令TreeMap,我认为你不能使用相同的实现来按值排序。但是你可以通过稍微不同的方法来完成任务:

public Map<String, Integer> countWords(List<String> words) {
    Map<String, Integer> result = new Map<>();
    for (String word : words) {
        if (result.containsKey(word)) {
            // the word is already in the map, increment the count
            int count = result.get(word) + 1;
            result.put(word, count);
        } else {
            result.put(word, 1);
        }
    }

    return result;
}

然后,您只需要对生成的地图的元素进行排序。您可以通过以下方式执行此操作:

public List<Map.Entry<String, Integer> sortMap(Map<String, Integer> map) {
    List<Map.Entry<String, Integer> elements = new LinkedList<>(map.entrySet());
    Collections.sort(elements, new Comparator<Map.Entry<String, Integer>>() {

        public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2 ) {
            return o1.getValue().compareTo(o2.getValue());
        }

    });
}

因此,您使用第一种方法来计算单词频率,使用第二种方法对其进行排序。


1
投票

您可以创建一个ArrayList并将每个条目存储在其中,如下所示:

ArrayList<Map.Entry<String, Integer> list = new new ArrayList(map.entrySet());

然后你可以使用比较器对arrayList进行排序,比较器按值来比较:

Collections.sort(list , new Comparator<Map.Entry<String, Integer>>() {

        public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2 ) {
            return o1.getValue().compareTo(o2.getValue());
        }

    });

然后您可以打印arrayList中的条目


1
投票

尝试这样的事情:

Set<Map.Entry<Integer, Integer>> sorted = 
      new TreeSet<Map.Entry<Integer, Integer>>(new Comparator<Map.Entry<Integer, Integer>> {
    public int compare(Map.Entry<Integer, Integer> first, Map.Entry<Integer, Integer> second) {
       return first.getValue().compareTo(second.getValue());
    }

    public boolean equals(Map.Entry<Integer, Integer> that) {
        return this.equals(that);
    }
});

这应该给你你想要的。

© www.soinside.com 2019 - 2024. All rights reserved.