我试图按降序计算字符串中的字母数。但我的代码只收集了我的一些信件。这是为什么?
代码:
import java.util.Iterator;
import java.util.TreeMap;
import java.util.TreeSet;
public class CharacterCount {
public static void main(String[] args)
{
TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>();
String s = "holy brown cow now";
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
int count = 1;
if(tm.containsKey(ch)){
count=tm.get(ch) + 1;
}
tm.put(ch, count);
}
TreeSet<CharItem> ts = new TreeSet<CharItem>();
Iterator<Character> it = tm.descendingKeySet().iterator();
while (it.hasNext()){
char ch = (char) it.next();
int count = tm.get(ch);
CharItem ci= new CharItem(ch, count);
ts.add(ci);
}
Iterator<CharItem> it2 = ts.iterator();
while(it2.hasNext()){
CharItem ci=it2.next();
System.out.println(ci.getCh() + " occured " + ci.getCount() + " times");
}
}
}
class CharItem implements Comparable<CharItem>{
private int count;
private char ch;
public CharItem(char c, int i){
count = i;
ch = c;
}
public char getCh() {
return this.ch;
}
public int getCount() {
return this.count;
}
@Override
public int compareTo(CharItem b) {
return b.count - this.count ;
}
}
在上面添加了charitem
答案 0 :(得分:0)
问题在于类CharItem
,因为它应该被修改。
public class CharItem implements Comparable<CharItem>{
private int count;
private char ch;
public CharItem(char c, int i){
count = i;
ch = c;
}
public char getCh() {
return this.ch;
}
public int getCount() {
return this.count;
}
@Override
public int compareTo(CharItem o) {
int result = Integer.compare(count, o.count);
return result == 0 ? Character.compare(ch, o.ch) : result;
}
@Override
public boolean equals(Object o) {
return o instanceof CharItem && ((CharItem)o).ch == ch;
}
}
方法compareTo
必须与equals
方法一致,如同两个对象通过equals()
相等,那么compareTo()
必须返回零,否则如果这些对象存储在TreeMap/TreeSet
他们不会表现得很好。您需要在代码中使用Iterator<CharItem> it2 = ts.descendingIterator();
:
public static void main(String[] args) {
TreeMap<Character, Integer> tm = new TreeMap<Character, Integer>();
String s = "holy brown cow now";
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
int count = 1;
if (tm.containsKey(ch)) {
count = tm.get(ch) + 1;
}
tm.put(ch, count);
}
TreeSet<CharItem> ts = new TreeSet<CharItem>();
Iterator<Character> it = tm.descendingKeySet().iterator();
while (it.hasNext()) {
char ch = (char) it.next();
int count = tm.get(ch);
CharItem ci = new CharItem(ch, count);
ts.add(ci);
}
Iterator<CharItem> it2 = ts.descendingIterator();
while (it2.hasNext()) {
CharItem ci = it2.next();
System.out.println(ci.getCh() + " occured " + ci.getCount() + " times");
}
}
然后你会得到:
o occured 4 times
w occured 3 times
occured 3 times
n occured 2 times
y occured 1 times
r occured 1 times
l occured 1 times
h occured 1 times
c occured 1 times
b occured 1 times
我认为这就是你想要的。另一种选择是尝试:
TreeSet<CharItem> ts = new TreeSet<CharItem>(Collections.reverseOrder());
这将以相反的顺序插入元素本身,比较器返回的符号实际上会反转。