List 获取前N条数据

发布于:2023-09-15 ⋅ 阅读:(101) ⋅ 点赞:(0)

1.使用for循环遍历

    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

    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方法    

    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

    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());
    }


网站公告

今日签到

点亮在社区的每一天
去签到