【问题标题】:Sorting a tuple(int, string) and save the string values in a string array对 tuple(int, string) 进行排序并将字符串值保存在字符串数组中
【发布时间】:2019-07-28 00:03:01
【问题描述】:

我正在使用此代码对单词和整数对进行排序,按整数对对进行排序(降序)

对元组进行排序后,如何仅将字符串值保存在 String [] 数组中?

我在这里找到了代码,因为我是新来的,所以无法在同一页面上发表评论。 (@艾略特弗里施)

How to sort the words by their frequency

 public Tuple(int count, String word) {
    this.count = count;
    this.word = word;
}

@Override
public int compareTo(Tuple o) {
    return new Integer(this.count).compareTo(o.count);
}
public String toString() {
    return word + " " + count;
}

}

public static void main(String[] args) {
String[] words = { "the", "he", "he", "he", "he", "he", "he", "he",
        "he", "the", "the", "with", "with", "with", "with", "with",
        "with", "with" };
// find frequencies
Arrays.sort(words);
Map<String, Integer> map = new HashMap<String, Integer>();
for (String s : words) {
    if (map.containsKey(s)) {
        map.put(s, map.get(s) + 1);
    } else {
        map.put(s, 1);
    }
}
List<Tuple> al = new ArrayList<Tuple>();
for (Map.Entry<String, Integer> entry : map.entrySet()) {
    al.add(new Tuple(entry.getValue(), entry.getKey()));
}
Collections.sort(al);
System.out.println(al);

}

【问题讨论】:

  • 仅供参考: new Integer(this.count).compareTo(o.count) 应该是 Integer.compare(this.count, o.count)
  • 您真的在问如何创建String[],然后迭代al 列表以将值分配给数组吗?你试过简单的for 循环吗?

标签: java arrays tuples


【解决方案1】:

如果它必须是数组,你去:


        Collections.sort(al);
        String[] wordsResult = new String[al.size()];
        int i = 0;
        for (Tuple tuple : al) {
            wordsResult[i++] = tuple.word;
        }
        Stream.of(wordsResult).forEach(System.out::println);
        System.out.println(al);

【讨论】:

    【解决方案2】:

    您也可以使用 Stream-API 对这个 ArrayList 进行排序

     Object[] arr = al.stream()
    .sorted(Comparator.comparing(Tuple::getCount).reversed())//sort counts as per count
    .map(Tuple::getWord) //mapping to each count to word
    .toArray(); //collect all words to array
     System.out.println(Arrays.toString(arr));
    

    你也可以把这些话收藏到List&lt;String&gt;

    List<String> arr =al.stream() 
    .sorted(Comparator.comparing(Tuple::getCount).reversed())//sort counts as per count
    .map(Tuple::getWord) //mapping to each count to word
    .collect(Collectors.toList())//Collect to List
    

    【讨论】:

      猜你喜欢
      • 2014-10-28
      • 2015-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-05
      • 2016-07-18
      相关资源
      最近更新 更多