Today we will see how to
find list of Strings that contains only alphabets. In this post I did
this with and without using regular expression and using java 8 streams.
package com.interviewCodes.string;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class AlphaString {
public static void main(String[] args) {
List<String> strlist = Arrays.asList("abc12#", "abc", "def", "gh$45", "ghi");
//
find the string that contains only alphabets
System.out.println("List of Strings :: " + strlist);
System.out.println("Without using reg exp :: " + alphaStrings(strlist));
System.out.println("Using reg exp :: " + alphaStringsUsingRegExp(strlist));
System.out.println("Using Java 8 :: " + alphaStringsUsingJava8(strlist));
}
// Without
using REG EXP
public static List<String> alphaStrings(List<String> list) {
List<String> alphaStrlist = new ArrayList<>();
for (String str : list) {
char[] chars = str.toCharArray();
for (char c : chars) {
if (!Character.isLetter(c))
continue;
if (str.endsWith(Character.toString(c)))
alphaStrlist.add(str);
}
}
return alphaStrlist;
}
// Using REG
EXP
public static List<String> alphaStringsUsingRegExp(List<String> list) {
List<String> alphaStrList = new ArrayList<>();
for (String str : list) {
if (str.matches("[a-zA-Z]*$"))
alphaStrList.add(str);
}
return alphaStrList;
}
// Using
Java8
public static List<String> alphaStringsUsingJava8(List<String> list) {
return list.stream()
.filter(i -> i.chars().allMatch(Character::isLetter))
.collect(Collectors.toList());
}
}
Please let me know if there any other better way to do this
and also correct me if any mistakes in this post.
Thanks for reading :)