使用分隔符

时间:2017-07-01 03:42:10

标签: java arrays

我的数据格式如下:

["DATA1-1","DATA1-2","DATA1-3","DATA1-4","","DATA2-1","DATA2-2","DATA2-3","DATA2-4","","DATA3-1","DATA3-2","DATA3-3","DATA3-4",""]

我想将这个数组拆分成几个数组,其中分隔符应该是一个空项("")。像这样:

[["DATA1-1","DATA1-2","DATA1-3","DATA1-4"],["DATA2-1","DATA2-2","DATA2-3","DATA2-4"],["DATA3-1","DATA3-2","DATA3-3","DATA3-4"]].  

这是我提出的代码:

private List<List<String>> retrieveData(List<String> arrayIn)
{

    List<List<String>> subArrays = new ArrayList<>();

    List<String> tempArrays = new ArrayList<>();

    for(int i=0; i<arrayIn.size(); i++)
    {
        if(!airwayIn.get(i).equals("") && i != (airwayIn.size()-1) )
        {
            tempArrays.add(airwayIn.get(i));
        }
        else if (airwayIn.get(i).equals("") || i == (airwayIn.size()-1) )
        {
            subArrays.add(tempArrays);
            tempArrays = new ArrayList<>();
        }
    }

    return subArrays;
}

但我想知道是否有更优雅的代码可以做到这一点。例如,这是我在Swift中使用的:

let subArrays: [[String]] = airwayIn.split(separator: "").map{Array($0)}

谢谢!

2 个答案:

答案 0 :(得分:0)

这是使用Java 8的解决方案:

private List<List<String>> retrieveData (List<String> list)
{
    // get all the indexes of the empty strings
    int [] indexes = 
                  Stream.of(IntStream.of(-1), IntStream.range(0, list.size())
                  .filter(i -> list.get(i).equals("")), IntStream.of(list.size()))
                  .flatMapToInt(s -> s).toArray();

    // Split into sub lists based on the indexes
    List<List<String>> subLists = 
              IntStream.range(0, indexes.length - 2)
                     .mapToObj(i -> list.subList(indexes[i] + 1, indexes[i + 1]))
                     .collect(Collectors.toList());

    System.out.println(subLists);
    return subLists;
}

<强>输出

[[DATA1-1, DATA1-2, DATA1-3, DATA1-4], [DATA2-1, DATA2-2, DATA2-3, DATA2-4], [DATA3-1, DATA3-2, DATA3-3, DATA3-4]]

答案 1 :(得分:0)

您可以使用简单的for循环来执行此操作,例如:

String[] array  = {"DATA1-1","DATA1-2","DATA1-3","DATA1-4","","DATA2-1","DATA2-2","DATA2-3","DATA2-4","","DATA3-1","DATA3-2","DATA3-3","DATA3-4",""};
List<List<String>> result = new ArrayList<>();
List<String> elements = new ArrayList<>();
for(String s : array){
    if("".equals(s) && !elements.isEmpty()){
        result.add(elements);
        elements = new ArrayList<>();
    }else{
        elements.add(s);
    }
}
//Add the remaining elements
if(!elements.isEmpty()){
    result.add(elements);
}
System.out.println(result);