ในการนับการเกิดขึ้นของอักขระแต่ละตัวในสตริงโดยใช้ Hashmap โค้ด Java มีดังต่อไปนี้ -
ตัวอย่าง
import java.io.*;
import java.util.*;
public class Demo{
static void count_characters(String input_str){
HashMap<Character, Integer> my_map = new HashMap<Character, Integer>();
char[] str_array = input_str.toCharArray();
for (char c : str_array){
if (my_map.containsKey(c)){
my_map.put(c, my_map.get(c) + 1);
}else{
my_map.put(c, 1);
}
}
for (Map.Entry entry : my_map.entrySet()){
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
public static void main(String[] args){
String my_str = "Joe Erien ";
System.out.println("The occurence of every character in the string is ");
count_characters(my_str);
}
} ผลลัพธ์
The occurence of every character in the string is 2 r 1 e 2 E 1 i 1 J 1 n 1 o 1
คลาสชื่อ Demo มีฟังก์ชันชื่อ 'count_characters' ที่นี่สร้าง hashmap ที่จะเก็บตัวละครและจำนวนของมัน ฟังก์ชันนี้จะวนซ้ำผ่านสตริงและตรวจสอบการนับของทุกอักขระ ในฟังก์ชันหลัก สตริงจะถูกกำหนด และฟังก์ชันถูกเรียกใช้บนสตริงนี้ และข้อความที่เกี่ยวข้องจะแสดงบนคอนโซล