简体   繁体   English

字符串排序空值

[英]String sorting null values

I have a string arraylist with some null values and some strings.我有一个字符串数组列表,其中包含一些null值和一些字符串。 I don't want to sort the arraylist but I should sort the arraylist such that null values comes last.我不想对数组列表进行排序,但我应该对数组列表进行排序,以便空值排在最后。 Lets say arraylist is {1,2,null,6,5,null, 3} , I should get null values last {1,2,6,5,3,null,null} .假设 arraylist 是{1,2,null,6,5,null, 3} ,我应该最后获得空值{1,2,6,5,3,null,null}

Solution , I currently have: Right now, I am constructing new arraylist and If the value is null , I am not pushing it to new list otherwise I am adding it to new arraylist.解决方案,我目前有:现在,我正在构建新的数组列表,如果值为null ,我不会将其推送到新列表,否则我会将其添加到新的数组列表。

Any other better solution?还有其他更好的解决方案吗?

Thanks for the help.谢谢您的帮助。

If you are using Java 8, you can easily build the comparator you need:如果您使用的是 Java 8,则可以轻松构建所需的比较器:

Arrays.sort(stringArray, Comparator.nullsLast(Comparator.naturalOrder()));

But if you not using java 8 you can have a comparator like below但是如果你不使用 java 8 你可以有一个像下面这样的比较器

public class StringNullComparator implements Comparator<String> {
    public int compare(String stringOne, String stringTwo) {
        if (stringOne != null && stringTwo != null)
            return stringOne.compareTo(stringTwo);
        return (stringOne == stringTwo)?0:(stringOne==null? 1 : -1);
    }
}

And you can use at stated below您可以在以下说明中使用

Arrays.sort(stringArray, new StringNullComparator());   

Custom Comparator to pass to sort:要传递给排序的自定义比较器:

public class StringComparator implements Comparator<String> {
    public int compare(String s1, String s2) {
        if (s1 != null && s2 != null)
            return s1.compareTo(s2);
        return (s1 == null) ? 1 : -1;
    }
}

then:然后:

Collectios.sort(list, new StringComparator());

If you want to avoid explicitly iterating over the whole list you could use ArrayList.indexOf() to find the null values, then remove() them.如果您想避免显式迭代整个列表,您可以使用 ArrayList.indexOf() 来查找空值,然后使用 remove() 它们。 If you want to keep the values in the list you can then just add a null value to the end of the list.如果您想保留列表中的值,则只需在列表末尾添加一个空值即可。 However I would imagine this approach is not great in terms of performance if this is a concern.但是,如果这是一个问题,我认为这种方法在性能方面并不是很好。

您可以使用apache 中的 NullComparator

Collections.sort(list, new NullComparator());

如何构造新的数组列表,如果它是一个真正的值,则将其添加到新列表中,如果它是一个空增量一个计数器。最后添加等于计数器值的空值。

If you want to sort null to the end and keep the order for the non-null elements this Comparator would do that :如果您想将 null 排序到最后并保持非 null 元素的顺序,此Comparator会这样做:

class CompareStrings implements Comparator<String> {

    @Override
    public int compare(String o1, String o2) {
        if (o1 == null && o2 != null)
            return 1;
        if (o2 == null && o1 != null)
            return -1;
        return 0;
    }   
}

If both String are null or non-null they will compare equal.如果两个String都为空或非空,它们将比较相等。 If only one is null it will compare as smaller than the non-null one.如果只有一个为空,它将比非空的小。

How about:怎么样:

class MyInteger implements Comparator<Integer> {
    public int compare(Integer arg0, Integer arg1) {
        if(arg1 == null) {
            return -1;
        }
        return 0;
    }
}

And we can use it like:我们可以像这样使用它:

List<Integer> al = new ArrayList<Integer>();
al.add(1);
al.add(2);
al.add(null);
al.add(6);
al.add(5);
al.add(null);
al.add(3);

Collections.sort(al, new MyInteger());

All other solutions involve sorting.所有其他解决方案都涉及排序。 As you mentioned, you don't really need sorting.正如你提到的,你真的不需要排序。 In case time complexity is a concern, you can use the following linear time solution (in-place):如果时间复杂度是一个问题,您可以使用以下线性时间解决方案(就地):

  public static <T> void nullsToEndInPlace(List<T> l) {
    int i = 0;
    int j = l.size() - 1;
    while (i < j) {
      T left = l.get(i);
      T right = l.get(j);
      if (left != null) {
        i++;
      } else if (right == null) {
        j--;
      } else {
        l.set(i, right);
        l.set(j, null);
        i++;
        j--;
      }
    }
  }

Try this.尝试这个。

    List<String> list = new ArrayList<>();
    list.add("BR64");
    list.add("SWG620");
    list.add("");
    list.add("sw0");
    list.add("R124");
    list.add("R219");
    list.add("TaGh20");
    list.add("SW6505");
    list.add("");
    list.add(null);
    list.add("SW_6505");
    list.add("swd_157");
    list.add("localhost");
    list.add("qaGh20_241");
    list.add("gen");
    list.add(null);
    list.add("taGh20");
    list.add("zen");
    list.add("QWG");
    list.add("SWG62_");
    list.add("SWG620");

    Collections.sort(list, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            if (o1 != null && o2 != null && o1.length() > 0 && o2.length() > 0) {
                return (Character.toLowerCase(o1.charAt(0)) == Character.toLowerCase(o2.charAt(0)))
                        ? o1.compareTo(o2)
                        : (Character.toLowerCase(o1.charAt(0)) + o1.substring(1))
                                .compareTo((Character.toLowerCase(o2.charAt(0)) + o2.substring(1)));
            } else {
                return (o1 == o2) ? 0 : ((o1 == null || o1 == "") ? 1 : -1);
            }
        }
    });
    System.out.println(list);

Output-:[BR64, gen, localhost, QWG, qaGh20_241, R124, R219, SW6505, SWG620, SWG620, SWG62_, SW_6505, sw0, swd_157, TaGh20, taGh20, zen, , , null, null]输出-:[BR64, gen, localhost, QWG, qaGh20_241, R124, R219, SW6505, SWG620, SWG620, SWG62_, SW_6505, sw0, swd_157, TaGh20, taGh20, zen, null]

Both list.sort() and sorted() have a key parameter to specify a function to be called on each list element prior to making comparisons. list.sort()sorted()都有一个关键参数,用于指定在进行比较之前对每个列表元素调用的函数。

For example, here's a case-insensitive string comparison:例如,这是一个不区分大小写的字符串比较:

sorted("This is a test string from sohan".split(), key=str.lower)                                                                                                                   
['a', 'from', 'is', 'sohan', 'string', 'test', 'This'] 

here, key=str.lower() will convert every string to lower case and then sort the result.在这里, key=str.lower()会将每个字符串转换为小写,然后对结果进行排序。

For more info about sorting click here有关排序的更多信息,请单击此处

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

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