1.使用for循环遍历
java
public static void main(String[] args) {
int limit = 5;
List<Integer> oldList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7);
List<Integer> newList = Lists.newArrayList();
if (oldList.size() <= limit) {
newList.addAll(oldList);
return;
}
for (int i = 0; i < limit; i++) {
newList.add(oldList.get(i))
}
}
2.使用Stream API
java
public static void main(String[] args) {
int limit = 5;
List<Integer> oldList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7);
List<Integer> newList = new ArrayList<>(limit);
if (oldList.size() <= limit) {
newList.addAll(oldList);
return;
}
newList = oldList.stream().limit(limit).collect(Collectors.toList());
}
3.使用subList方法
java
public static void main(String[] args) {
int limit = 5;
List<Integer> oldList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7);
List<Integer> newList = new ArrayList<>(limit);
if (oldList.size() <= limit) {
newList.addAll(oldList);
return;
}
newList = oldList.subList(0,limit);
}
4.使用Apache Commons Collections
java
public static void main(String[] args) {
int limit = 5;
List<Integer> oldList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7);
List<Integer> newList = new ArrayList<>(limit);
if (oldList.size() <= limit) {
newList.addAll(oldList);
return;
}
CollectionUtils.addAll(newList, oldList.iterator());
}