Perhaps there is another solution that can also solve your problem in a more java-8 way:
- using a
map
to record the count of the duplicated strings and then
- directly traverse the array from the very beginning till the end and
- once the string is not duplicated, we get it right there.
That could be like:
public static void main(String... args) {
String[] arr = {"Dog", "Cat", "Dog", "Wolf", "lion"};
Map<String, Long> stringCountMap = Arrays.stream(arr)
.collect(Collectors.groupingBy(s -> s, Collectors.counting()));
for (String s : arr) {
if (stringCountMap.get(s) == 1) {
System.out.println("The first non-duplicate string: " + s);
break;
}
}
}
Also you can turn to LinkedHashMap
as others mentioned to keep the order to avoid traverse the original array again as:
private static void another(String[] arr) {
Map<String, Long> stringCountMap = Arrays.stream(arr)
.collect(Collectors.groupingBy(s -> s, LinkedHashMap::new, Collectors.counting()));
for (String s : stringCountMap.keySet()) {
if (stringCountMap.get(s) == 1) {
System.out.println("The first non-duplicate string: " + s);
break;
}
}
}
The output will always be:
The first non-duplicate string: Cat