--Introduction --Premise ――What you want to achieve ――What I tried --Problem
Suddenly, I want to study Map and List! !! I thought </ b>, so I thought about the issues and made it. I stumbled upon the roles of Map and List and conversion. Even if I searched online, I couldn't find any good results, so I've put together my own, so I'll write an article.
――What you want to achieve
--Identification of the most frequently used string for n arbitrary string type inputs (n_1 n_2 n_3 ... ... n).
――What I tried
--Implemented [key: input string, value: number of appearances] as Map <String, Integer> map = Map
--Problem --Map system [HashMap, LinkedHashMap, TreeMap] basically has no order of elements. --Like map [0], you cannot retrieve the value by index.
The contents implemented based on the solution are as follows.
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) {
//Input detection
Scanner sc = new Scanner(System.in);
String count = sc.nextLine();
String[] line = sc.nextLine().split(" ");
//Map making
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);
}
}
//Get map entry → store in list
List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>();
for (Map.Entry<String, Integer> entry : map.entrySet()){
list.add(entry);
}
//Compare the value of entry in list → sort
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();
}
}
}
--Summary ――It is important to be aware of the role of each class --Map throws a function to List when an associative array or an ordered array is needed ――Because I couldn't do this, I didn't understand when I first tried to sort the Map.
Recommended Posts