How do I join two lists in Java?

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

    Use a Helper class.

    I suggest:

    public static  Collection addAll(Collection dest, Collection... src) {
        for(Collection c : src) {
            dest.addAll(c);
        }
    
        return dest;
    }
    
    public static void main(String[] args) {
        System.out.println(addAll(new ArrayList(), Arrays.asList(1,2,3), Arrays.asList("a", "b", "c")));
    
        // does not compile
        // System.out.println(addAll(new ArrayList(), Arrays.asList(1,2,3), Arrays.asList("a", "b", "c")));
    
        System.out.println(addAll(new ArrayList(), Arrays.asList(1,2,3), Arrays.asList(4, 5, 6)));
    }
    
        

    提交回复
    热议问题