import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Test.sortString("i am eileen lee lee lee am");
Test.sortFrequency("i i i i i am eileen lee lee lee am");
}
public static void sortString(String s){
String[] sArray = s.split(" ");
Arrays.sort(sArray, new Comparator1());
for(String item:sArray)
{
System.out.println(item);
}
}
public static void sortFrequency(String s){
String[] sa = s.split(" ");
Hashtable<String, Integer> ht = new Hashtable<String, Integer>();
List<String> list = new ArrayList<String>();
for(String item:sa)
{
if(ht.containsKey(item))
ht.put(item, ht.get(item)+1);
else{
ht.put(item, 0);
list.add(item);
}
}
Collections.sort(list, new Comparator2(ht));
for(String str : list){
System.out.println(str);
}
}
}
class Comparator2 implements Comparator<String>{
private Hashtable<String, Integer> ownht;
public Comparator2(Hashtable<String, Integer> ht){
this.ownht = ht;
};
@Override
public int compare(String o1, String o2) {
// TODO Auto-generated method stub
if(this.ownht.get(o1) < this.ownht.get(o2)){
return 1;
}else if(this.ownht.get(o1) == this.ownht.get(o2)){
return 0;
}else{
return -1;
}
}
}
class Comparator1 implements Comparator<String>{
@Override
public int compare(String o1, String o2) {
// TODO Auto-generated method stub
if(o1.charAt(o1.length()-1) > o2.charAt(o2.length() - 1))
return 1;
else if(o1.charAt(o1.length()-1) == o2.charAt(o2.length() - 1))
return 0;
else
return -1;
}
}
sort
最新推荐文章于 2024-05-30 20:22:14 发布