Reputation: 79
If I am given an ArrayList of strings, i.e. {"hello", "goodbye", "morning", "night"}
, how do I check how many a
's, b
's, c
's, etc. there are in the list?
The method must return an array of int
s, where position [0] is the numbers of a
's, etc. For example, the returnArray[1] = 1
, because there is one b
in the list. Is there a better way to do this than simply hardcoding each letter?
public static int[] getLetters( ArrayList<String> list) {
int [] result = new int[25];
if(list.contains('a')) {
result[0] = result[0] + 1;
}
return result;
}
Is there a better way than repeating the above strategy 25 more times?
Upvotes: 4
Views: 4274
Reputation: 50550
You can rely on a map
and the Character
class as follows:
import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
class C {
public static void main(String[] args) {
String w1 = "samefoo";
String w2 = "barsame";
ArrayList<String> al = new ArrayList<String>();
al.add(w1);
al.add(w2);
// this is your method --->
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
for(String str: al) {
for(int i = 0; i < str.length(); ++i) {
char k = str.charAt(i);
if(map.containsKey(k)) {
map.put(k, map.get(k) + 1);
} else {
map.put(k, 1);
}
}
}
// <---
for(char c: map.keySet()) {
System.out.println(c + ":" + map.get(c));
}
}
}
Obviously, all the ones not in the map have implicitly 0 as counter.
Upvotes: 0
Reputation: 34460
With java 8, you could do it this way:
List<String> list = new ArrayList<>(Arrays.asList("hello", "goodbye", "morning", "night"));
Map<String, Long> map = list.stream()
.flatMap(word -> Arrays.stream(word.split("")))
.collect(Collectors.groupingBy(
letter -> letter,
Collectors.counting()));
System.out.println(map); // {r=1, b=1, t=1, d=1, e=2, g=3, h=2, i=2,
// y=1, l=2, m=1, n=3, o=4}
Building the required array from this map is left as an excercise to the reader ;)
Upvotes: 0
Reputation: 347244
You can use the char
as a means to address the array, for example...
ArrayList<String> list = new ArrayList<>(Arrays.asList(new String[]{"hello", "goodbye", "morning", "night"}));
int[] results = new int[26];
for (String value : list) {
for (char c : value.toCharArray()) {
// 'a' is the lowest range (0), but the ascii for 'a' is 97
results[c - 'a'] += 1;
}
}
Which results in...
[0, 1, 0, 1, 2, 0, 3, 2, 2, 0, 0, 2, 1, 3, 4, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0]
nb: This will only work for lower case characters, if you have any upper case characters, you'll get an array out of bounds error. You could put range checking in for each character to make sure it's between a
and z
, but that's up to you
Upvotes: 9
Reputation: 23
Yo can convert your Array toCharArray() and then you can compare each letter with the alphabet you want.
Upvotes: 0