1

I am really new to java 8.I am trying to create a HashMap from a stream that has showNames in it. My issues is that the names can be repetitive and they can appear multiple times, which means they have to be mapped on the same key, I have tried with filter after mapping but I am not sure what condition to put. x->x.equals(x)? how the stream showNames looks like:

LOTR, Lucifer, Breaking Bad, LOTR, Exorcist, The Godfather, The Godfather, Lucifer, etc

The hash map should have as keys the name of the show and as value the times the string appears in the stream

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
Diana G
  • 261
  • 3
  • 15
  • 1
    Have you tried using [`Stream::distinct`](https://docs.oracle.com/javase/10/docs/api/java/util/stream/Stream.html#distinct())? – Flown May 22 '18 at 09:08
  • 1
    Possible duplicate of [Count int occurrences with Java8](https://stackoverflow.com/questions/23925315/count-int-occurrences-with-java8) – AxelH May 22 '18 at 09:14
  • I was first mapping it and then thinking to filter it, however after I mapped it I could'n filter correctly – Diana G May 22 '18 at 09:15

1 Answers1

5

What you want is to group actually:

Map<String, Long> result = yourList.stream()
              .collect(Collectors.groupingBy(
                 Function.identity(), 
                 Collectors.counting()))
Eugene
  • 117,005
  • 15
  • 201
  • 306
  • 3
    @HadiJ .. *and as value the times the string appears in the stream* – Eugene May 22 '18 at 09:10
  • use `Collectors.summingInt(e->1)` instead `Collectors.counting()` – Hadi J May 22 '18 at 09:15
  • Bear in mind that this is a `HashMap` by implementation detail only. It could theoretically be changed to any other map implementation. So if a `HashMap` is the only structure which is appropriate, you might want to be explicit. – Michael May 22 '18 at 09:16
  • @Michael correct, if OP says she needs a `HashMap` exactly, I will change this – Eugene May 22 '18 at 09:17
  • 4
    @HadiJ it's a very tiny performance improvement (unless you can tell that the bottleneck is there, I would not change it). Besides, `counting` is way more idiomatic and simpler to read for beginners – Eugene May 22 '18 at 09:18
  • _The `summingInt` approach will accumulate the count in `int` rather than Integer and thus will not require any `boxing/unboxing`. It will be at its best if objects repeat a very large number of times_ see [this](https://stackoverflow.com/questions/30451284/counting-elements-of-a-stream) – Hadi J May 22 '18 at 09:24
  • 2
    @HadiJ exactly what I said in the comment... and if you upgrade to java-9, this is already fixed. I would stick with `counting` – Eugene May 22 '18 at 09:25