【问题标题】:Compare two string arrays by index(stream)按索引(流)比较两个字符串数组
【发布时间】:2021-11-24 15:30:36
【问题描述】:

我想比较两个字符串数组(大小相同),并根据其索引检查 mainArray 是否包含 subArray 中的元素;

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

这看起来很丑陋,哪里有使用 stream.filter 或其他东西的解决方案?

【问题讨论】:

  • 只是关于命名法的提示:这些是列表,而不是数组。数组很少在 Java 中直接使用,可能用于原始类型除外。此外,从 Java 9 开始,List.of(...) 主要是 Arrays.asList(...) 的替代品(它在某些地方的行为有点不同,但在大多数情况下,它是直接替代品)。

标签: java list lambda stream


【解决方案1】:

无论两个数组(在您的情况下实际上是Lists)大小是否相等,这都将起作用。

  • 首先stream mainArray。
  • 然后flatMap子数组
  • filter 那些 mainArray 字符串包含 subArray 字符串之一的情况。
  • 计算成功并返回是否等于主数组大小。
boolean flag = mainArray.stream()
        .flatMap(str -> subArray.stream()
                .filter(sa -> str.contains(sa)))
        .count() == mainArray.size();

这是一个使用单个sub Array 和多个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);
}

打印

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

【讨论】:

    【解决方案2】:

    我找到了这个解决方案

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-28
      • 2013-06-17
      相关资源
      最近更新 更多