程序以按插入频率的排序方式打印字符串

时间:2012-06-16 19:51:50

标签: java list sorting collections

让我们说我已经插入了 asd dsa asd dsa kk km ka km kk
因此我想打印O / P为:
ASD:2个
DSA:2
公里:2
KK:2
KA:1

这里我提供的代码已经实现了

    import java.util.*;
class Subex1
{
    public static void main(String[] args) 
    {
        try{
        List<String> l=new ArrayList<String>();
        for(String s:args)
        {
            l.add(s);
        }
        Set<String> unique = new HashSet<String>(l);
        for (String key : unique) {
            int count=Collections.frequency(l, key);
            System.out.println(key + ": " +count );
        }
    }
        catch(Exception e)
        {
            e.printStackTrace();
        }

    }
}

但是这里的O / P就是这样的 asd:2
ka:1
dsa:2
kk:2
km:2

1 个答案:

答案 0 :(得分:2)

使用比较器使用Collections.sort(originalSourceUniqueSet, new MyComparator());

进行排序

并实现像

这样的比较器
class MyComparator implements Comparator<String>{
 List<String> originalSource;
 public MyComparator(List<String> originalSource){
  this.originalSource=originalSource;
 }
 @Override
 public int compare(String str1, String str2){
    int result = Collections.frequency(originalSource, str1) -  Collections.frequency(originalSource, str2);
    //if same frequency then sort based on natural ordering
    if(result == 0 ){
        return str1.compareTo(str2);
    }
    return result;
 }
}