private ListcomputeArticleTfidf(String content, int titleLength) { Map tm = new HashMap (); List parse = NlpAnalysis.parse(content); for (Term term : parse) { double weight = getWeight(term, content.length(), titleLength); if (weight == 0) continue; Keyword keyword = tm.get(term.getName()); if (keyword == null) { keyword = new Keyword(term.getName(), term.natrue().allFrequency, weight); tm.put(term.getName(), keyword); } else { keyword.updateWeight(1); } } TreeSet treeSet = new TreeSet (tm.values()); ArrayList arrayList = new ArrayList (treeSet); if (treeSet.size() <= nKeyword) { return arrayList; } else { return arrayList.subList(0, nKeyword); } }
考虑到怕许问题,其实java中接口Set有众多实现类,而HashSet和TreeSet是最常用的两个,通过TreeSet实现排序的2种方式:
1.通过TreeSet(Comparator super E> comparator) 构造方法指定TreeSet的比较器进行排序;
2.使用TreeSet()构造方法,并对需要添加到set集合中的元素实现Comparable接口进行排序;
跟踪源代码,可以发现上面的例子,实用的就是第二种方式,查看Keyword类:
public class Keyword implements Comparable
可以看到该类以下方法:
@Override public int compareTo(Keyword o) { if (this.score < o.score) { return 1; } else { return -1; } }
接下来我们实现一下第一种方式:
实体类:
public class AA { private int num; public int getNum() { return num; } public void setNum(int num) { this.num = num; } public String toString() { return "AA:" + this.getNum() + ","; } }
比较器:
import java.util.Comparator; public class MyComparator implements Comparator{ public int compare(AA a1,AA a2) { if (f1.getNum() > f2.getNum()) { return 1; } else if (a1.getNum() == a2.getNum()) { return 0; } else { return -1; } } }
接下来就是使用了:
TreeSetset = new TreeSet(new MyComparator());
这样在set.add()元素时就会根据自己定义比较器进行排序了。
程序猿行业技术生活交流群:181287753(指尖天下),欢迎大伙加入交流学习。