Giới thiệu
Ví dụ này demo cách đếm tần suất xuất hiện của mỗi ký tự trong chuỗi nhập từ EditText, sử dụng HashMap<Character, Integer> và hiển thị kết quả lên TextView.
Bước 1 & 2: Tạo dự án và Giao diện
Giao diện: EditText nhập chuỗi, nút Lưu, TextView hiển thị kết quả.
Bước 3: MainActivity.java
package com.example.andy.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
EditText name;
TextView textview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = findViewById(R.id.name);
textview = findViewById(R.id.textview);
findViewById(R.id.save).setOnClickListener(v -> {
String input = name.getText().toString();
if (!input.isEmpty()) {
// HashMap lưu ký tự -> số lần xuất hiện
HashMap<Character, Integer> charCountMap = new HashMap<>();
for (char c : input.toCharArray()) {
charCountMap.put(c, charCountMap.getOrDefault(c, 0) + 1);
}
// Format kết quả đẹp hơn
StringBuilder result = new StringBuilder();
for (Map.Entry<Character, Integer> entry : charCountMap.entrySet()) {
result.append(entry.getKey())
.append(": ")
.append(entry.getValue())
.append("\n");
}
textview.setText(result.toString());
Toast.makeText(this, "Đã đếm", Toast.LENGTH_LONG).show();
} else {
name.setError("Nhập chuỗi");
}
});
}
}
Giải thích thuật toán
- Duyệt từng ký tự trong chuỗi:
toCharArray(). getOrDefault(key, 0): Lấy giá trị hiện tại hoặc 0 nếu chưa có, sau đó +1.- Độ phức tạp: O(n) với n = độ dài chuỗi.
- Kết quả in ra dạng:
a: 3\nb: 1\n...
Chạy ứng dụng

TextView hiển thị từng ký tự và số lần xuất hiện.