对元组(int,字符串)进行排序并将字符串值保存在字符串数组中

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

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

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

如何按频率对单词进行排序

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

}


陪伴而非守候
浏览 136回答 2
2回答

白衣非少年

如果它必须是数组,你去:&nbsp; &nbsp; &nbsp; &nbsp; Collections.sort(al);&nbsp; &nbsp; &nbsp; &nbsp; String[] wordsResult = new String[al.size()];&nbsp; &nbsp; &nbsp; &nbsp; int i = 0;&nbsp; &nbsp; &nbsp; &nbsp; for (Tuple tuple : al) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; wordsResult[i++] = tuple.word;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; Stream.of(wordsResult).forEach(System.out::println);&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(al);

温温酱

您还可以使用 Stream-API 对这个 ArrayList 进行排序&nbsp;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&nbsp;System.out.println(Arrays.toString(arr));你也可以把这些话收藏起来List<String>List<String> arr =al.stream()&nbsp;.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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java