1

I have a requirement where i have to split array list of strings to multiple smaller lists based on a delimiter. Lets say my list contains

["This list contains"],
["What I need"],
["bla bla"],
["bla bla"],
["bla bla"],
["bla bla"],
["Found"],
["some more"],
["irrelevant"],
["data"]

Whenever i find What I need, i have to slice the list from that part till i find the string found

so My resultant sublist should be of the form

["bla bla"],
["bla bla"],
["bla bla"],
["bla bla"]
johnnesto
  • 31
  • 1
  • 4

3 Answers3

1

If you're using Java 9 or later, you can use the Stream API with the dropWhile and takeWhile methods:

    List<String> list = List.of(
            "This list contains",
            "What I need",
            "bla bla",
            "bla bla",
            "bla bla",
            "bla bla",
            "Found",
            "some more",
            "irrelevant",
            "data"
    );

    list.stream()
            .dropWhile(str -> !str.equals("What I need"))
            .skip(1) // to discard the start marker
            .takeWhile(str -> !str.equals("Found"))
            .forEach(System.out::println);
    
    /*
     * Output:
     * bla bla
     * bla bla
     * bla bla
     * bla bla
     */

This is assuming that the start and end markers only appear once in the original list.

Tim Moore
  • 8,958
  • 2
  • 23
  • 34
0

The search result will be within the "result" list, and the original array will be spliced.

String searchTermStart = "Andy", searchTermEnd = "Bill";
ArrayList<String> rows = new ArrayList(List.of("Eric", "Andy", "Joan", "Marc", "Bill", "Phil"));

boolean addToOther = false; 
List<String> result = new ArrayList<String>();

Iterator<String> iterator = rows.iterator(); 

while (iterator.hasNext()) { 
    String row = iterator.next();  
    if (row.equals(searchTermStart)) {  
        result.add(row);
        iterator.remove();                
        addToOther = true;
    } else if (addToOther) { 
        result.add(row);
        if (row.equals(searchTermEnd)) {
            addToOther = false;
        }
        iterator.remove();
    }
}
Omeri
  • 187
  • 2
  • 16
-2

I think use methods string.split().

String[] data = string.split(" ");
csalmhof
  • 1,820
  • 2
  • 15
  • 24
bang
  • 17
  • 1