侧边栏壁纸
博主头像
996 Worker's Blog博主等级

祇園精舎の鐘の聲, 諸行無常の響き有り。

  • 累计撰写 215 篇文章
  • 累计创建 55 个标签
  • 累计收到 25 条评论

目 录CONTENT

文章目录

Convert List<Integer>to int[] array with Java 8 stream.

996Worker
2023-01-29 / 0 评论 / 0 点赞 / 111 阅读 / 975 字

Intro

To convert List with foundamental data type such as int, we can use stream feature of the Java 8:

public int[] getLeastNumbers(int[] arr, int k) {
        if (k == 0 || arr.length == 0) {
            return new int[0];
        }

        PriorityQueue<Integer> pq = new PriorityQueue<>();

        for (int num : arr) {
            pq.add(num);
        }

        List<Integer> list = new LinkedList<>();

        for (int i = 0; i < k; i++) {
            list.add(pq.poll());
        }

        return list.stream().mapToInt(Integer::intValue).toArray();
    }

In the other hand, we can also achieve this with loop:

public int[] toIntArray(List<Integer> list) {
	int[] ret = new int[list.size()];
    for (int i = 0; i < ret.length; i++) {
    	ret[i]= list.get(i);
     }
     return ret;
}
0

评论区