package org.example;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class StringUniqueService {
public String getFirstUniqueElement(String[] elements) {
List<String> uniqueElements = Arrays.stream(elements)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.stream()
.filter(entry -> entry.getValue().equals(1L))
.map(Map.Entry::getKey)
.collect(Collectors.toList());
return Arrays.stream(elements)
.filter(uniqueElements::contains)
.findFirst().orElse(null);
}
}
package org.example;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class StringUniqueServiceTest {
StringUniqueService underTest = new StringUniqueService();
@Test
void testGetFirstUniqueElement_ShouldReturnCorrectValue_GivenNotEmptyStringArray() {
String [] elements = new String[] {
"a", "a", "b", "c", "d"
};
String firstUniqueElement = underTest.getFirstUniqueElement(elements);
assertEquals(firstUniqueElement, "b");
}
}