gpt4 book ai didi

java - 如何对重复字符串进行计数和排序

转载 作者:行者123 更新时间:2023-12-05 00:58:43 27 4
gpt4 key购买 nike

我有一串名字

String str = "A. Walker, L. Gordon, C. Riley, L. Gordon";

我需要计算名称出现次数并将出现次数从大到小排序。

我已经完成了计数部分,但我还需要对其进行排序。

String[] array = str.split(", ");        

List asList = Arrays.asList(array);
Set<String> mySet = new HashSet<String>(asList);
for(String s: mySet)
System.out.println(s + " " +Collections.frequency(asList,s));

输出应该是这样的

L. Gordon 2, A. Walker 1, C. Riley 1

最佳答案

你可以这样做:

public class Test {
static class NameFreq {
public NameFreq(String name, int freq) {
this.name = name;
this.freq = freq;
}
String name;
int freq;
@Override
public String toString() {
return name + " " + freq;
}
}
public static void main(String[] args) throws Exception {
String str = "A. Walker, L. Gordon, C. Riley, L. Gordon";
Map<String, NameFreq> map = new HashMap<>();
String[] array = str.split("\\s*,\\s*");
for(String name : array) {
NameFreq nameFreq = map.get(name);
if( nameFreq==null )
map.put(name, new NameFreq(name, 1));
else
nameFreq.freq++;
}

List<NameFreq> list = new ArrayList<>(map.values());
Collections.sort(list, new Comparator<NameFreq>() {
@Override
public int compare(NameFreq o1, NameFreq o2) {
return Integer.compare(o2.freq, o1.freq);
}
});

System.out.println(list);
//output: [L. Gordon 2, A. Walker 1, C. Riley 1]
}
}

关于java - 如何对重复字符串进行计数和排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43281559/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com