ภาพรวม
ตัวอย่างนี้สาธิตวิธีหา สตริงที่ซ้ำอันดับสอง (Second most repeated string) ในอาร์เรย์บน Android โดยใช้ HashMap นับจำนวนครั้ง แล้วจัดเรียงเพื่อหาค่าที่ซ้ำอันดับสอง
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
เปิด Android Studio → File → New Project → กรอกรายละเอียดที่จำเป็น
ขั้นตอนที่ 2: จัดรูปแบบหน้าจอ (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:gravity="center"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/text"
android:textSize="30sp"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
ในโค้ดข้างต้น ใช้ TextView เพื่อแสดงสตริงที่ซ้ำอันดับสอง
ขั้นตอนที่ 3: เขียนโค้ด Java (src/MainActivity.java)
package com.example.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;
public class MainActivity extends AppCompatActivity {
TextView textView;
String[] strArray = {"aaa", "aaa", "bbb", "ccc", "bbb"};
@RequiresApi(api = Build.VERSION_CODES.P)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HashMap<String, Integer> hashMap = new HashMap<>();
HashSet<String> hashSet = new HashSet<>();
// นับจำนวนครั้งที่แต่ละสตริงปรากฏ
for (int i = 0; i < strArray.length; i++) {
if (hashMap.containsKey(strArray[i])) {
hashMap.put(strArray[i], hashMap.get(strArray[i]) + 1);
} else {
hashMap.put(strArray[i], 1);
}
}
// เก็บคีย์ที่ไม่ซ้ำ
for (String name : hashMap.keySet()) {
hashSet.add(name);
}
List<String> list = new ArrayList<>(hashSet);
TextView textView = findViewById(R.id.text);
// แสดงค่าที่ index size-2 (อันดับสองจากท้าย)
textView.setText(list.get(list.size() - 2));
}
}
การทดสอบแอปพลิเคชัน
เชื่อมต่ออุปกรณ์ Android จริงกับคอมพิวเตอร์ ใน Android Studio เปิดไฟล์ Activity แล้วคลิกไอคอน Run จากแถบเครื่องมือ เลือกอุปกรณ์มือถือของคุณ แล้วตรวจสอบหน้าจอ

ข้อมูล: {"aaa", "aaa", "bbb", "ccc", "bbb"}
- aaa: 2 ครั้ง
- bbb: 2 ครั้ง
- ccc: 1 ครั้ง
สตริงที่ซ้ำอันดับสองคือ "bbb" (หรือ "aaa" ขึ้นอยู่กับลำดับใน HashSet)
หมายเหตุ
โค้ดตัวอย่างนี้มีข้อจำกัด: HashSet ไม่รับประกันลำดับ การหา "อันดับสอง" ที่แม่นยำควรจัดเรียง Map ตามค่า (frequency) ก่อน