|
| 1 | +package com.baeldung.hazelcast.jet; |
| 2 | + |
| 3 | +import java.util.List; |
| 4 | +import java.util.Map; |
| 5 | + |
| 6 | +import static com.hazelcast.jet.Traversers.traverseArray; |
| 7 | +import static com.hazelcast.jet.aggregate.AggregateOperations.counting; |
| 8 | +import static com.hazelcast.jet.function.DistributedFunctions.wholeItem; |
| 9 | + |
| 10 | +import com.hazelcast.jet.Jet; |
| 11 | +import com.hazelcast.jet.JetInstance; |
| 12 | +import com.hazelcast.jet.pipeline.Pipeline; |
| 13 | +import com.hazelcast.jet.pipeline.Sinks; |
| 14 | +import com.hazelcast.jet.pipeline.Sources; |
| 15 | + |
| 16 | +public class WordCounter { |
| 17 | + |
| 18 | + private static final String LIST_NAME = "textList"; |
| 19 | + |
| 20 | + private static final String MAP_NAME = "countMap"; |
| 21 | + |
| 22 | + private Pipeline createPipeLine() { |
| 23 | + Pipeline p = Pipeline.create(); |
| 24 | + p.drawFrom(Sources.<String> list(LIST_NAME)) |
| 25 | + .flatMap(word -> traverseArray(word.toLowerCase() |
| 26 | + .split("\\W+"))) |
| 27 | + .filter(word -> !word.isEmpty()) |
| 28 | + .groupingKey(wholeItem()) |
| 29 | + .aggregate(counting()) |
| 30 | + .drainTo(Sinks.map(MAP_NAME)); |
| 31 | + return p; |
| 32 | + } |
| 33 | + |
| 34 | + public Long countWord(List<String> sentences, String word) { |
| 35 | + long count = 0; |
| 36 | + JetInstance jet = Jet.newJetInstance(); |
| 37 | + try { |
| 38 | + List<String> textList = jet.getList(LIST_NAME); |
| 39 | + textList.addAll(sentences); |
| 40 | + Pipeline p = createPipeLine(); |
| 41 | + jet.newJob(p) |
| 42 | + .join(); |
| 43 | + Map<String, Long> counts = jet.getMap(MAP_NAME); |
| 44 | + count = counts.get(word); |
| 45 | + } finally { |
| 46 | + Jet.shutdownAll(); |
| 47 | + } |
| 48 | + return count; |
| 49 | + } |
| 50 | + |
| 51 | +} |
0 commit comments