标签:
(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 Test {
/**
* 分析一个字符串中各个单词出现的频率
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String str="Hello Hello Hello Hello World My First Unit Test";
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;
}
}
结果:
(3)
import java.util.Scanner;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
System.out.print("输入字符串:");
String str = scanner.nextLine();
String[] strs = str.split(" ");
System.out.print("倒序后的字符串为:");
for(int i = strs.length-1;i>=0;i--)
{
System.out.print(strs[i]+" ");
}
System.out.print("\n");
}
}
结果:
标签:
原文地址:http://www.cnblogs.com/3137102414hua/p/5322970.html