如何在 Android 中查找序列中重复次数第二多的字符串?

androidmobile developmentapps/applications

本示例演示了如何在 Android 中查找序列中重复次数第二多的字符串。

步骤 1 − 在 Android Studio 中创建一个新项目,转到"文件"->"新建项目",并填写所有必需的详细信息以创建新项目。

步骤 2 − 将以下代码添加到 res/layout/activity_main.xml。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://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:gravity="center"
android:layout_height="match_parent"
android:tools:context=".MainActivity>
android:textView
android:id="@+id/text"
android:textView   android:textSize="30sp"
      android:layout_width="match_parent"
      android:layout_height="match_parent" />
</LinearLayout>

在上面的代码中,我们用一个文本视图来显示数组中第二长的序列。

步骤 3 − 将以下代码添加到 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()) {
         String key = name.toString();
         String value = hashMap.get(name).toString();
         hashSet.add(key);
      }
      List<String> list=new ArrayList<>(hashSet);
      TextView textView = findViewById(R.id.text);
      textView.setText(list.get(list.size()-2));
   }
}

让我们尝试运行您的应用程序。假设您已将实际的 Android 移动设备连接到电脑。要从 Android Studio 运行该应用程序,请打开项目的某个活动文件,然后点击工具栏上的"运行"图标。选择您的移动设备作为选项,然后勾选将显示默认屏幕"减号"的移动设备。

点击此处下载项目代码


相关文章