繁体   English   中英

从字符串数组中删除空值的最佳方法

[英]Best way to remove null values from string array

下面是删除空值的两种方法,哪一种是最好的方法?

public static String[] clean(final String[] v) {
    List<String> list = new ArrayList<String>(Arrays.asList(v));
    list.removeAll(Collections.singleton(null));
    return list.toArray(new String[list.size()]);
}

public static String[] clean(final String[] v) {
    List<String> list = new ArrayList<String>(v.length);
     for (String aString : v)
        {
            if (aString != null)
            {
                list.add(aString);
            }
        }
    return list.toArray(new String[list.size()]);
}

为了从单个字符串中删除空值,我会使用这样的正则表达式,

private static Pattern pattern = Pattern.compile("(?i)[(\\[{]?null[)\\]}]?");

    public static String removeNullString(String value) {
        if (StringUtils.isEmpty(value)) {
            return StringUtils.EMPTY;
        }

        Matcher matcher = pattern.matcher(value);
        return matcher.replaceAll(StringUtils.EMPTY);
    }

它覆盖了字符串中的所有“空”和空字符。

要从 Java 7 中的字符串数组中删除空值

String[] firstArray = {"test1", "", "test2", "test4", "", null};

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

    for(String s : firstArray) {
       if(s != null && s.length() > 0) {
          list.add(s);
       }
    }

    firstArray = list.toArray(new String[list.size()]);

要从 Java 8 中的字符串数组中删除空值

String[] firstArray = {"test1", "", "test2", "test4", "", null};

firstArray = Arrays.stream(firstArray)
                     .filter(s -> (s != null && s.length() > 0))
                     .toArray(String[]::new); 

在性能方面,最好尽量减少当前代码块(即方法)范围之外的调用。 此外,由于与大多数其他指令相比,内存分配相对较慢,因此避免创建对象通常是一个目标。 在性能方面我能想到的最好的(我选择让它足够灵活以接受任何类型的数组):

public <T> T[] removeNulls(Class<T> type, final T[] original){

    // first, shift all non-null instances to the head, all nulls to the end.
    int nonNullCount=0;
    T tempT = null;

    for(int i=0; i < original.length; i++){
        if(original[i] != null){
            nonNullCount++;
        }else if(i != original.length - 1){
            // Swap the next non-null value with this null value
            int j = i + 1;
            // In case there are multiple null values in a row
            // scan ahead until we find the next non-null value
            while(j < original.length && (tempT = original[j]) == null){
                j++;
            }
            original[nonNullCount] = tempT;
            if(tempT != null){
                nonNullCount++;
            }
            if(j < original.length){
                original[j] = null;
            }

            i = j - 1;
        }
    }

    // The case where there are no nulls in the array
    if(nonNullCount == original.length){
        return original;
    }

    final T[] noNulls = (T[]) Array.newInstance(type,nonNullCount);
    System.arraycopy(original,0,noNulls,0,nonNullCount);
    return  noNulls;
}

但是我不确定为什么在性能不太可能成为问题的情况下,为什么您希望 3 或 4 行的这种复杂性来做同样的事情。 你需要有巨大的数组才能看到我的代码和你的干净示例之间的任何好处(如果有的话)。

在 Java 8 中,您应该能够执行以下操作:

List<String> list = new ArrayList<String>(Arrays.asList(v));
list.removeIf(Objects::isNull);
return list.toArray(new String[list.size()]);

如果你想在同一个空间里做,我会建议以下解决方案。 但最终数组也将具有相同的大小。 我的意思是它不会缩小尺寸,但所有元素都会以相同的顺序聚合。

   public static void removeNullFromArray(String[] args) {
      int location = 0;
      for(int i=0;  i<args.length; i++){
         String arg = args[i];
         if(arg!=null){
            if(location<i){
               args[location] = arg;
               args[i] = null;
            }
            location++;
         }
      }
   }

使用流和 lambda 的 Java 8 代码。 从数组中过滤非空值并转换为列表。

Arrays.stream(arr).filter(Objects::nonNull).collect(Collectors.toList());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM