-
Notifications
You must be signed in to change notification settings - Fork 0
/
Main.java
89 lines (72 loc) · 3 KB
/
Main.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> inputList = new ArrayList<String>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.println(
"Select an output format\n Enter 1 to print number of words per letter\n Enter 2 to see list of words per letter");
int outputChoice = Integer.parseInt(br.readLine());
System.out.println("Enter your string array input:");
String[] line = br.readLine().split(",");
for (int i = 0; i < line.length; i++) {
inputList.add(line[i].trim());
}
if (outputChoice == 1) {
printNumberOfWordsPerLetter(inputList);
} else {
printWordsAndNumberPerLetter(inputList);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
private static void printNumberOfWordsPerLetter(List<String> fruits) {
HashMap<Character, Integer> fruitsMap = getWordsPerLetter(fruits);
fruitsMap.entrySet().forEach(entry -> {
System.out.println(entry.getKey() + ": " + entry.getValue());
});
}
private static void printWordsAndNumberPerLetter(List<String> fruits) {
HashMap<Character, List<String>> multiMap = storeWordsPerLetter(fruits);
for (char ch = 'A'; ch <= 'Z'; ++ch) {
if (multiMap.containsKey(ch)) {
System.out.println(ch + ": " + multiMap.get(ch).size());
multiMap.get(ch).forEach(fruitInList -> {
System.out.println(1 + " " + fruitInList.replace("\"", ""));
});
} else {
System.out.println(ch + ": " + 0);
}
}
}
private static HashMap<Character, Integer> getWordsPerLetter(List<String> fruits) {
HashMap<Character, Integer> fruitsMap = new HashMap<>();
for (char ch = 'A'; ch <= 'Z'; ++ch) {
fruitsMap.put(ch, 0);
}
for (String fruit : fruits) {
char fruitBeginsWith = fruit.charAt(1);
int currentValue = fruitsMap.get(fruitBeginsWith);
fruitsMap.replace(fruitBeginsWith, currentValue + 1);
}
return fruitsMap;
}
private static HashMap<Character, List<String>> storeWordsPerLetter(List<String> fruits) {
HashMap<Character, List<String>> multiMap = new HashMap<>();
for (String fruit : fruits) {
char firstLetter = fruit.charAt(1);
if (multiMap.containsKey(firstLetter)) {
multiMap.get(firstLetter).add(fruit);
} else {
List<String> alphabetFruitsList = new ArrayList<>();
alphabetFruitsList.add(fruit);
multiMap.put(firstLetter, alphabetFruitsList);
}
}
return multiMap;
}
}