How do I join two lists in Java?

后端 未结 30 2053
旧巷少年郎
旧巷少年郎 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:11

    You could do it with a static import and a helper class

    nb the generification of this class could probably be improved

    public class Lists {
    
       private Lists() { } // can't be instantiated
    
       public static List join(List... lists) {
          List result = new ArrayList();
          for(List list : lists) {
             result.addAll(list);
          }
          return results;
       }
    
    }
    

    Then you can do things like

    import static Lists.join;
    List result = join(list1, list2, list3, list4);
    

提交回复
热议问题