LoginSignup
0
2

More than 3 years have passed since last update.

【Java】文字の出現回数を調べる

Last updated at Posted at 2020-07-31

目次

  • はじめに
  • 前提
    • 実現したいこと
    • やってみたこと
    • 問題
    • 解決方法
  • 実装内容
  • 終わりに

はじめに

ふと、MapとかListとか勉強したい!!と思ったので課題考えて作ってみましたが
MapとListの役割とか変換とかでかなり躓きました。
オンラインで検索してもあんましいいの出てこなかったので、自分なりにまとめたので記事にします。

前提

  • 実現したいこと
    • n個の任意の文字列型入力(n_1 n_2 n_3... ...n)に対し、最も多く登場した文字列の特定。
  • やってみたこと

    • Map map = Map();として、[key:入力文字列, value:登場回数]を実装。
    • mapを[value]でソートして一番最初の[key]を取り出せばいいじゃん!
  • 問題

    • Map系[HashMap, LinkedHashMap, TreeMap]は、基本的には要素に順番を持たない。
    • map[0]のように、インデックスでは値を取り出せない。
  • 解決方法

    • Map.Entryクラスを利用して、マップのkeyとvalueの組み合わせを取得できる。
    • List内にEntryオブジェクトを格納して、List[i]のEntryのvalueでソートができる。

実装内容

解決方法をもとに実装した内容が以下です。

CountMain.java

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;

public class CountMain {

    public static void main(String[] args) {

        // 入力検知
        Scanner sc = new Scanner(System.in);
        String count = sc.nextLine();
        String[] line = sc.nextLine().split(" ");

        // マップ作製
        Map<String, Integer> map = new HashMap<String, Integer>();
        for(int i=0; i<line.length; i++){
            if(!map.containsKey(line[i])){
                map.put(line[i], 1);
            } else {
                int tmp = map.get(line[i]);
                map.remove(line[i]);
                map.put(line[i], tmp+1);
            }
        }

        // mapのエントリを取得→listへ格納
        List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>();
        for (Map.Entry<String, Integer> entry : map.entrySet()){
                list.add(entry);
        }

        // list内entryのバリューを比較→ソート
        for (int i = 0; i < list.size(); i++){
            for (int j = list.size()-1; j > i; j--){
                if (list.get(j).getValue() > list.get(j-1).getValue()){
                    Map.Entry<String, Integer> tmpEntry = list.get(j-1);
                    list.set(j-1, list.get(j));
                    list.set(j, tmpEntry);
                }
            }
        }

        System.out.print(list.get(0).getKey());
        try {
            int i = 1;
            while( list.get(i).getValue() == list.get(i-1).getValue() ){
                System.out.print(" " + list.get(i).getKey());
                i++;
            }
        } catch (IndexOutOfBoundsException e){
            return;
        } finally {
            System.out.println("");
            sc.close();
        }
    }
}

終わりに

0
2
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2