Java Program to Find the First Repeated Word in a String
In this section, we will show you two different ways to find first repeated word in a given String in Java.
1. Using For loop and Map
2. Using Java 8 Streams
Example 1. Using For loop and Map
import java.util.LinkedHashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
String str ="kotlin java python java go python " +
"go java python java go python go";
Map<String, Integer> map = new LinkedHashMap<>();
String[] words = str.split(" ");
for (String word : words) {
if (map.containsKey(word)) {
map.put(word, map.get(word) + 1);
} else {
map.put(word, 1);
}
if (map.get(word) > 1) {
System.out.println(word);
break;
}
}
}
}
Here the logic is simple,
split() method is used to split the String based on whitespace and it returns an Array of String.
Iterate over String Array and check whether map contains specific key. If map contains specific key get the value(count) and put the key and value(+1) inside LinkedHashMap. LinkedHashMap don't allow for duplicate keys. The second value should just replace the previous value. The main advantage of utilizing LinkedHashMap is that it maintains and tracks the order of insertion.
Finally, printing the first element of LinkedHashMap, that is we print a first element which value is greater than one.
Console Output:
java
java
Example 2: Using Java 8 Streams
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
String str ="kotlin java python java go python " +
"go java python java go python go";
Optional<String> firstRepeatedWord =
Arrays.stream(str.split(" ")).collect(Collectors
.groupingBy(Function.identity(),LinkedHashMap::new,
Collectors.counting()))
.entrySet().stream().filter(m ->m.getValue()>1)
.map(m ->m.getKey())
.findFirst();
if(firstRepeatedWord.isPresent()) {
System.out.println(firstRepeatedWord.get());
}
}
}
stream() method accepts a mandatory parameter array which is the array of whose elements are to be converted into a sequential stream and returns a Sequential Stream from the array passed as the parameter.
split() method splits the string based on whitespace.
Java Stream collect() performs a mutable reduction operation on the elements of the stream. This is a terminal operation.
The groupingBy() method of Collectors class in Java are used for grouping objects by some property and storing results in a Map instance. In order to use it, we always need to specify a property by which the grouping would be performed.
identity() is a static method of the Function interface that always returns the input argument.
Here, the main advantage of utilizing LinkedHashMap is that it maintains and tracks the order of insertion.
Collectors counting() method is used to count the number of elements passed in the stream as the parameter.
entrySet() returns a set view of all the entries from the LinkedHashMap.
Using filter() method we filter the elements whose value is greater than one.
Using map() method we are converting Stream of Entry<String,Long> to Stream of String.
Finally, we are printing the first element.
Console Output:
java
java
More Interesting topics,