Home > OS >  Compare two string arrays by index(stream)
Compare two string arrays by index(stream)

Time:11-25

I want to compare two arrays(same sized) of strings and check that mainArray contains elements in subArray depending on its index;

public static void main(String[] args) {
    List<String> mainArray = Arrays.asList("Red book", "Yellow bird", "Green sky");
    List<String> subArray = Arrays.asList("Red", "Yellow", "Green");

    boolean flag = false;
    for (int i = 0; i < mainArray.size(); i  ) {
        flag = mainArray.get(i).contains(subArray.get(i));
        if(!flag){
            break;
        }
    }
}
//returns true

this looks ugly is where any solution with stream.filter or something?

CodePudding user response:

This will work whether the two arrays (actually Lists in your case) are equal size or not.

  • first stream the mainArray.
  • then flatMap the subArray
  • the filter those cases where the mainArray string contains one of the subArray strings.
  • count the successes and return whether it equals the main array size.
boolean flag = mainArray.stream()
        .flatMap(str -> subArray.stream()
                .filter(sa -> str.contains(sa)))
        .count() == mainArray.size();

Here is a demo using a single sub Array and multiple main arrays

List<String> mainArray1 =
        List.of("Red book", "Purple bird", "Blue sky");
List<String> mainArray2 = List.of("Red book", "Blue bird",
        "Blue sky", "Violet flower");
List<String> mainArray3 = List.of("Red book", "Blue bird");
List<String> mainArray4 =
        List.of("Blue book", "Blue bird", "Blue sky");
List<String> mainArray5 = List.of("Red book", "Purple color");
List<String> mainArray6 = List.of("Red book", "Blue bird",
        "Blue sky", "Orange orange");

List<List<String>> lists = List.of(mainArray1, mainArray2,
        mainArray3, mainArray4, mainArray5, mainArray6);

List<String> subArray = List.of("Red", "Yellow", "Blue",
        "Orange", "Violet", "Green");

int i = 1;
for (List<String> mainArray : lists) {
    
    boolean flag = mainArray.stream()
            .flatMap(str -> subArray.stream()
                    .filter(sa -> str.contains(sa)))
            .count() == mainArray.size();
    
    System.out.printf("mainArray%d %b%n", i  , flag);
}

Prints

mainArray1 false
mainArray2 true
mainArray3 true
mainArray4 true
mainArray5 false
mainArray6 true

CodePudding user response:

I found this solution

IntStream.range(0, mainArray.size()).allMatch(i -> mainArray.get(i).contains(subArray.get(i)));
  • Related