Need to get the number of letters in an ArrayList of strings

If I am given an ArrayList of strings, i.e. {"hello", "goodbye", "morning", "night"}how to check how much a, b's, cetc. is there in the list?

The method should return an array ints, where position [0] is the numbers a' s, etc. For example, returnArray[1] = 1because there is one in the list b, is there a better way to do this than just hard-coding 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?

+4
source share
4 answers

You can use charas a means to access 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;
    }
}

As a result ...

[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: , , . , , a z,

+8

Yo Chararray(), .

0

map Character :

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));
        }
    }
}

, , , 0 .

0

java 8 :

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}

;)

0

Source: https://habr.com/ru/post/1608618/


All Articles