Home > Net >  Find alphanumeric strings from ArraList using Java 8 Streams
Find alphanumeric strings from ArraList using Java 8 Streams

Time:07-09

List<String> list = Arrays.asList("ABC","123ABC","def","def45","2GHI","u3ht","zxy","t12pp", "kkk");

Note: print only alphanemeric strings - 123ABC, def457, 2GHI, u3ht, tt12pp

I tried as below but not working.

List<String> alphanNist = list.sream().filpter(s->s.matches("^[a-zA-Z0-9]*$").collect(Collectors.toList()); 

CodePudding user response:


import java.util.*;
import java.util.stream.Collectors;
import java.util.regex.*;

public class SO72918446 {
    public static void main(String args[]) {
        Pattern pattern = Pattern.compile("^(?=.*\\d)(?=.*[a-zA-Z]).{2,}$");
        List<String> list = Arrays.asList("ABC","123ABC","def","def45","2GHI","u3ht","zxy","t12pp", "kkk");
        List<String> alphanNist = list.stream().filter(s->pattern.matcher(s).matches()).collect(Collectors.toList()); 
        System.out.println(alphanNist);
    }
}

prints

In case you are wondering what the pattern means , you can refer regexr.com/6pdb2

[123ABC, def45, 2GHI, u3ht, t12pp]

However as comment says , if you want to match ABC as well, the Regex has to be modified a bit [(?:\s*[a-zA-Z0-9]{2,}\s*)*] would work there!

  • Related