java编程 写一段程序统计一段字符串中每一个单词的出现次数 并按照次数的倒序输出
2个回答
展开全部
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class MapSort {
public static void main(String[] args) {
String str = "adf adf ad adf adf ad ad f ad ad";
String[] items = str.split(" ");
Map<String, Integer> map = new HashMap<String, Integer>();
for (String s : items) {
if (map.containsKey(s))
map.put(s, map.get(s) + 1);
else {
map.put(s, 1);
}
}
List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>();
for (Entry<String, Integer> entry : map.entrySet()) {
list.add(entry);
}
Collections.sort(list, new EntryComparator());
for (Entry<String, Integer> obj : list) {
System.out.println(obj.getKey() + "\t" + obj.getValue());
}
}
}
class EntryComparator implements Comparator<Entry<String, Integer>> {
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return o1.getValue() > o2.getValue() ? 0 : 1;
}
}
参数你可以自己修改!
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class MapSort {
public static void main(String[] args) {
String str = "adf adf ad adf adf ad ad f ad ad";
String[] items = str.split(" ");
Map<String, Integer> map = new HashMap<String, Integer>();
for (String s : items) {
if (map.containsKey(s))
map.put(s, map.get(s) + 1);
else {
map.put(s, 1);
}
}
List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>();
for (Entry<String, Integer> entry : map.entrySet()) {
list.add(entry);
}
Collections.sort(list, new EntryComparator());
for (Entry<String, Integer> obj : list) {
System.out.println(obj.getKey() + "\t" + obj.getValue());
}
}
}
class EntryComparator implements Comparator<Entry<String, Integer>> {
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return o1.getValue() > o2.getValue() ? 0 : 1;
}
}
参数你可以自己修改!
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询