Is there a better way to write using Java 8 to populate LinkedHashMap?

I have a code that breaks a string of letters, creates a list with this and later, populate LinkedHashMap with Characterboth the Integerletter and its frequency. The code is as follows:

   List<String> values = Arrays.asList((subjects.split(",")));
            for (String value : values) {
                char v = value.charAt(0);
                map.put(v, map.containsKey(v) ? map.get(v) + 1 : 1);
            }
            map.put('X', 0);

How can I write this briefly with Java 8? Thank you

+4
source share
3 answers

Try the following:

LinkedHashMap<Character, Long> counts = Pattern.compile(",")
        .splitAsStream(subjects)
        .collect(Collectors.groupingBy(
                s -> s.charAt(0),
                LinkedHashMap::new,
                Collectors.counting()));

If you must have a counter Integer, you can wrap the collection counter as follows:

Collectors.collectingAndThen(Collectors.counting(), Long::intValue)

Another option (thanks @Holger ):

Collectors.summingInt(x -> 1)

As an additional note, you can replace the loop update as follows:

map.merge(v, 1, Integer::sum);
+8
source

One liner:

Map<String, Long> frequency = Arrays.stream(input.split("(?<=.)\\W*"))
    .collect(Collectors.groupingBy(s -> s, Collectors.counting()));

( ).

+3

, - :

Map<Character, Integer> result = new LinkedHashMap<>();
Arrays.asList(subjects.split(""))
      .stream().map(s -> s.charAt(0))
      .forEach(c -> result.put(c, result.containsKey(c) ? result.get(c) + 1 : 1));

Map<Character, Integer> result = new LinkedHashMap<>();
subjects.chars().mapToObj(c->(char)c)
    .forEach(c -> result.put(c, result.containsKey(c) ? result.get(c) + 1 : 1));
0
source

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


All Articles