亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

對元組(int,字符串)進行排序并將字符串值保存在字符串數組中

對元組(int,字符串)進行排序并將字符串值保存在字符串數組中

陪伴而非守候 2023-04-26 15:03:24
我正在使用此代碼對單詞和整數對進行排序,按整數對對進行排序(降序)對元組進行排序后,如何僅將字符串值保存在 String [] 數組中?我在這里找到了代碼,因為我是新來的,所以我無法在同一頁面上發表評論。(@Elliott Frisch)如何按頻率對單詞進行排序 public Tuple(int count, String word) {    this.count = count;    this.word = word;}@Overridepublic 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 frequenciesArrays.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);}
查看完整描述

2 回答

?
白衣非少年

TA貢獻1155條經驗 獲得超0個贊

如果它必須是數組,你去:



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


查看完整回答
反對 回復 2023-04-26
?
溫溫醬

TA貢獻1752條經驗 獲得超4個贊

您還可以使用 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<String>


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


查看完整回答
反對 回復 2023-04-26
  • 2 回答
  • 0 關注
  • 186 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號