【问题标题】:(Java) how to split an array by a certain value (string)?(Java)如何按某个值(字符串)拆分数组?
【发布时间】:2021-12-20 10:40:38
【问题描述】:

我有一个数组列表

[Type 1970, Type 1981, Type 1985, Type 1999]
[Type 1985, Type 1970, Type 1985, Type 1999]
[Type 1999, Type 1981, Type 1985, Type 1970]
[Type 1981, Type 1985, Type 1999, Type 1970]
[Type 1985, Type 1970, Type 1981, Type 1999]

我想拆分这些数组,同时仅提取特定模型类型(例如“Type 1999”)并提供计数。

这是我迄今为止想出的:

int counter = 0 
for(int i = 0; i < listOfTypes.length; i++){
String[] typesSearch = listOfTypes[i]
if(typesSearch != null) {
    if(typesSearch.equals("Type 1999")); {
counter++;
}
}

理想情况下,输出将是一个只有特定元素的新数组

{1999 型、1999 型、1999 型、1999 型} 等等

我想从这里我可以使用 length() 来获取这个新创建的数组中元素的计数

【问题讨论】:

  • typesSearch.equals("Type 1999") 将始终返回false,因为其中一个是String[],另一个是String。他们永远不可能平等。

标签: java arrays loops split


【解决方案1】:

我猜你有二维数组

    String[][] listOfTypes = {
            {"Type 1970", "Type 1981", "Type 1985", "Type 1999"},
            {"Type 1985", "Type 1970", "Type 1985", "Type 1999"},
            {"Type 1999", "Type 1981", "Type 1985", "Type 1970"},
            {"Type 1981", "Type 1985", "Type 1999", "Type 1970"},
            {"Type 1985", "Type 1970", "Type 1981", "Type 1999"}
    };

并计算Type 1999的出现次数

    int counter = 0;
    for (String[] typesSearch : listOfTypes) {
        for (String str : typesSearch) {
            if ("Type 1999".equals(str)) {
                counter++;
            }
        }
    }

或使用流

    int counter = (int) Arrays.stream(listOfTypes)
            .flatMap(typesSearch -> Arrays.stream(typesSearch))
            .filter(str -> str.equals("Type 1999"))
            .count();

【讨论】:

    【解决方案2】:

    我不知道你为什么想要那个;您当前的代码运行良好且高效。

    我猜你可以这样做:

    int count = (int) Arrays.stream(listOfTypes)
      .filter(x -> x.equals("Type 1999"))
      .count();
    

    如果你更喜欢这种风格,那就把自己打倒吧。在性能方面和可读性方面,它真的没有区别。但是,仅使用 Type 1999 条目创建一个中间数组,相对于无论如何计数而言,相当昂贵。这也是更多的代码。我不知道你为什么认为它是一个更好的解决方案而不是仅仅计数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多