ishallwin
ishallwin

Reputation: 310

PriorityQueue to Integer array

Any better way to convert PriorityQueue<int[]> pq to int[pq.size()][pq.peek().length]?

pq.toArray() gives an Object array and I am not so sure how to cast it to an int array.

One way I have tried is this :

PriorityQueue<int[]> pq = new PriorityQueue<int[]>();
int[] fin = new int[pq.size()];
for(int i=0;i<pq.size();i++) {
    fin[i] = pq.remove();
}

But I am looking for better time optimised solution.

Upvotes: 2

Views: 5139

Answers (2)

mamadaliev
mamadaliev

Reputation: 166

Using Java Stream API you can resolve this problem.

int[] fin = pq.stream()
    .map(String::valueOf)
    .mapToInt(Integer::parseInt)
    .toArray();

Example:

import java.util.Arrays;
import java.util.PriorityQueue;

public class Main {

    public static void main(String[] args) {
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        pq.add(1);
        pq.add(2);
        pq.add(3);

        int[] fin = convertToIntArray(pq);

        System.out.println(Arrays.toString(fin));
    }

    private static int[] convertToIntArray(PriorityQueue<Integer> pq) {
        return pq.stream()
                .map(String::valueOf)
                .mapToInt(Integer::parseInt)
                .toArray();
    }
}

Upvotes: 1

Matt
Matt

Reputation: 13923

The PriorityQueue implements Collection#toArray(T[] a) that you can use like this:

int[][] fin = pq.toArray(new int[0][0]);

Note that according to your question, you used the untyped version of toArray() which takes no argument and returns Object[]. This would be equivalent to toArray(new Object[0]).

Upvotes: 5

Related Questions