Issue
I'm trying to filter a list of strings which contains information about grid and grid. I have a pattern of letters which can be used to build a grid. So, how to get this grid using pattern?
4 3
AABC
CABB
ACCA
2,1; 0,0; 3,0;
I have to execute only grid (strings with letters) using pattern ABC as new list.
The result should be:
AABC
CABB
ACCA
My code:
List<String> data = Files.lines(Path.of("src/main/resources/file.txt")).collect(Collectors.toList());
List<String> grid = new ArrayList<>();
String pattern = "ABC";
data.forEach(System.out::println);
for(int i = 0; i <= data.size(); i++){
int finalI = i;
grid = data.stream().filter(s -> s.startsWith(pattern.split("")[finalI])).collect(Collectors.toList());
}
grid.forEach(System.out::println);
It's not filtering and throws index out of bounds.
Solution
If I understand it correctly, you want only the strings (the lines from your file) that contain only the letters you specify. If so, just create a charachter class with the valid letters and filter using String.matches
:
List<String> data = Files.readAllLines(Path.of("src/main/resources/file.txt"));
String regex = "[ABC]+";
List<String> grid = data.stream()
.filter(str -> str.matches(regex))
.collect(Collectors.toList());
grid.forEach(System.out::println);
Answered By - Eritrean
Answer Checked By - David Goodson (JavaFixing Volunteer)