2

假设我已经插入了
asd dsa asd dsa kk km ka km kk
因此我想将 O/P 打印为:
asd:2
dsa:2
km: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

4

1 回答 1

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;
 }
}
于 2012-06-16T20:01:41.157 回答