一种简单的方式是通过构造方
List<Plant> copy = new ArrayList<>(list);
注意:这里拷贝的是引用而不是元素,也就是说某个集合对元素进行修改,则两个集合都会影响
List<Integer> copy = new ArrayList<>(list);
所以对于通过构造方法的方法最好是拷贝不可变的类,例如Integer就是不可以修改的
通过addAll()
和通过构造方法一样是拷贝的引用而不是元素
通过Collections集合拷贝
List<Integer> source = Arrays.asList(1,2,3);
List<Integer> dest = Arrays.asList(4,5,6);
Collections.copy(dest, source);
注意这里做的是重写,而不是追加
通过java 8
List<String> copy = list.stream()
.collect(Collectors.toList());
第一个元素跳过
List<String> copy = list.stream()
.skip(1)
.collect(Collectors.toList());
添加过滤条件
List<String> copy = list.stream()
.filter(s -> s.length() > 10)
.collect(Collectors.toList());
List<Flower> flowers = list.stream()
.filter(f -> f.getPetals() > 6)
.collect(Collectors.toList());