[java]代码库
1.Main类
package s0223容器分拣存储;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
String str = "this is a cat and that is a dog";
String[] arry = str.split(" ");
Map<String, Letter> letters = new HashMap<String, Letter>();
// 未优化代码
// for (String temp : arry) {
// if (!letters.containsKey(temp))// HashMap.containsKey() 判断map中是否有这个键
// {
// letters.put(temp, new Letter());
//
// } else {
// Letter col = letters.get(temp);// 根据key,返回value
// col.setCount(col.getCount() + 1);
// }
// }
//优化代码***********************************************************************************
Letter col=null;
for (String temp : arry) {
if (null==(col=letters.get(temp)))// HashMap.containsKey() 判断map中是否有这个键
{
letters.put(temp, new Letter());
} else {
col.setCount(col.getCount() + 1);
}
}
//优化代码***********************************************************************************
letters.keySet().forEach(
(element) -> System.out.println("字母" + element + " 次数:"+ letters.get(element).getCount())
);
}
}
2.Letter类
package s0223容器分拣存储;
public class Letter {
private String name;
private int count;
public Letter()
{}
public Letter(String name, int count) {
this.name = name;
this.count = count;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}