Last active
December 15, 2020 18:31
-
-
Save jonyfs/507a37b31c035bfe3b735fd011a2c4e0 to your computer and use it in GitHub Desktop.
How to filter username in a List of Users ignoring accented characters.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.common.collect.ImmutableList; | |
import org.assertj.core.util.Strings; | |
import org.junit.Test; | |
import java.text.Normalizer; | |
import java.util.List; | |
import java.util.Locale; | |
import java.util.function.Predicate; | |
import java.util.regex.Pattern; | |
import java.util.stream.Collectors; | |
import static org.assertj.core.api.Assertions.assertThat; | |
public class FilterObjectStringStreamTest { | |
private static final Pattern PATTERN = Pattern.compile("\\p{InCombiningDiacriticalMarks}+"); | |
private List<User> getUsers() { | |
int i = 1; | |
return ImmutableList.of( | |
new User(i++, "João Saldanha"), | |
new User(i++, "João-Saldanha"), | |
new User(i++, "João:Saldanha"), | |
new User(i++, "Joao Silva"), | |
new User(i++, "Graça Maria"), | |
new User(i++, "Jorge Lourenço"), | |
new User(i++, "Fábio Saldanha"), | |
new User(i++, "Fabiano Gonçalves") | |
); | |
} | |
static class User { | |
int id; | |
String name; | |
public User(int id, String name) { | |
this.id = id; | |
this.name = name; | |
} | |
public int id() { | |
return id; | |
} | |
public String name() { | |
return name; | |
} | |
} | |
public static String deAccent(String str) { | |
return PATTERN.matcher(Normalizer.normalize(str, Normalizer.Form.NFD)).replaceAll(""); | |
} | |
public static Predicate<User> contains(String query) { | |
if (Strings.isNullOrEmpty(query)) | |
return user -> false; | |
return user -> deAccent(user.name()).toLowerCase(Locale.ROOT).contains(deAccent(query).toLowerCase(Locale.ROOT)); | |
} | |
private List<User> filterUser(String query) { | |
return getUsers().stream() | |
.filter(contains(query)) | |
.collect(Collectors.toList()); | |
} | |
@Test | |
public void filterUserTest() { | |
assertThat(filterUser("João SALDANha")).hasSize(1); | |
assertThat(filterUser("João-saldanha")).hasSize(1); | |
assertThat(filterUser("JoAo")).hasSize(4); | |
assertThat(filterUser("Graça")).hasSize(1); | |
assertThat(filterUser("Graca")).hasSize(1); | |
assertThat(filterUser("Fábi")).hasSize(2); | |
assertThat(filterUser(null)).isEmpty(); | |
assertThat(filterUser("")).isEmpty(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment