How do I join two lists in Java?

后端 未结 30 1758
旧巷少年郎
旧巷少年郎 2020-11-22 14:36

Conditions: do not modifiy the original lists; JDK only, no external libraries. Bonus points for a one-liner or a JDK 1.3 version.

Is there a simpler way than:

30条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 15:17

    public static  List merge(@Nonnull final List... list) {
        // calculate length first
        int mergedLength = 0;
        for (List ts : list) {
          mergedLength += ts.size();
        }
    
        final List mergedList = new ArrayList<>(mergedLength);
    
        for (List ts : list) {
          mergedList.addAll(ts);
        }
    
        return mergedList;
      }
    

提交回复
热议问题