Any null safe alternative to ArrayList.addAll?

后端 未结 4 1677
旧时难觅i
旧时难觅i 2021-02-02 09:35

I was refactoring some old code of mine that I\'ve written and I stumbeled on this code:

    List fullImagePool = new ArrayList<>();
           


        
相关标签:
4条回答
  • 2021-02-02 09:41

    Just write a small utility method:

    public static <E> void addAllIfNotNull(List<E> list, Collection<? extends E> c) {
        if (c != null) {
            list.addAll(c);
        }
    }
    

    so that you can write:

    List<OcmImageData> fullImagePool = new ArrayList<>();
    addAllIfNotNull(fullImagePool, style.getTestMH());
    addAllIfNotNull(fullImagePool, style.getTrousers());
    addAllIfNotNull(fullImagePool, style.getDetailRevers());
    // ...etc
    
    0 讨论(0)
  • 2021-02-02 09:42

    In Java 8 Use below code:-

    Optional.ofNullable(listToBeAdded).ifPresent(listToBeAddedTo::addAll)
    

    listToBeAdded - The list whose elements are to be added. listToBeAddedTo - The list to which you are adding elements using addAll.

    0 讨论(0)
  • 2021-02-02 09:46

    This refactors cleanly to

    for (OcmImageData elem : new List<OcmImageData>[] { style.getTestMH(), style.getTrousers() /* etc */}) {
        if (CollectionUtils.isNotEmpty(elem)) {
            fullImagePull.addAll(elem);
        }
    }
    

    To answer your original question, no, you will have to do your own null check. You can see Guava's methods will throw an NPE, and Apache's methods explicitly require the input to be not null.

    0 讨论(0)
  • 2021-02-02 10:01

    Using Java 8:

    List<OcmImageData> fullImagePool = Stream.of(style.getTestMH(), /* etc */)
                                             .filter(Objects::nonNull)
                                             .flatMap(l -> l.stream())
                                             .collect(Collectors.toList());
    
    0 讨论(0)
提交回复
热议问题