使用Hash Map統計每個每個字串出現的次數
@Test
public void test(){
final String VALUE = "qwertyuioppoiuytaDDdDsdfghjjhgvbnmmnbvvcclkjhgbvczxcvghk";
/* //將字串都轉換為小寫 ,是否區分大小寫
String VALUE1 = VALUE.toLowerCase();*/
// 使用HashMap計數
Map<Character,Integer> map = new HashMap<>();
//遍歷字符序列
for (int i =0; i<VALUE.length(); i++){
//獲取每個字符
char c = VALUE.charAt(i);
//將獲取的字符存放在HashMap中
//如果key不存在 就put
if (! map.containsKey(c)){
map.put(c,1);
}else{
//如果存在,取出原有的value值在+1
Integer sum = map.get(c);
map.put(c,sum+1);
}
}
//遍歷HashMap
map.forEach((k,v) ->{
System.out.println(k+"-->"+v);
});
/* //遍歷HashMap
Set<Map.Entry<Character, Integer>> entrySet = map.entrySet();
for (Map.Entry<Character, Integer> entry : entrySet){
System.out.println(entry.getKey()+"-->" + entry.getValue());
}*/
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/238049.html
標籤:java
上一篇:群暉DS218+部署GitLab
