Search code examples
javaarrayscollectionstoarray

Convert Collection to int[] array


There are two existing methods named getDetails(...). One expects a minimum of one mandatory parameter and the other expects a collection (doesn't validate the content/size of the collection).

The problem is that the collection is sometimes passed as empty and according to my business case, I always expect a minimum of one value, to be passed. So, I need to make that method private, which accepts Collections.

// There are two params, to make sure that at-least one is passed by the caller

public static CustomerContext getDetails(int id, int... ids) { 
   Collection<Integer> idCollection = Instream.of(ids).boxed().collect(Collectors.toSet());
   if(!idCollection.contains(id)){
       idCollection.add(id);
   }
   return getDetails(idCollection);
}

I'm planning to make the below method scope to private so that the callers would not call this method with Zero attributes.

public static CustomerContext getDetails(Collection<Integer> idCollection) {
    return getDetails(idCollection,false);
}

One of the caller methods is passing Collection object to getDetails like below,

CustomerContext.getDetails(id.getDetails().values());

The id.getDetails() is as below,

public Map<Id,Integer> getDetails(){
    return Collections.unmodifiableMap(details);
}

I'm looking for a way to convert the collection id.getDetails().values() into int[] for passing to getDetails(int id,int... ids) instead of calling getDetails(Collection<Integer> idCollection).

I could cast the collection to Integer[] as below,

(Integer[])id.getDetails().values().toArray()

I did not find a way to cast Collection to int[].

Any suggestions would be of great help.

I already referred to some of the existing questions but did not succeed to solve my issue:

Conversion of collection to int array

Convert java.util.Collections to Integer array


Solution

  • Collection to Integer[]

    When you need to get a result of type Integer[], you have to provide a function as an argument while calling toArray(), there's no need to apply casting (if you're not passing a parameter toArray() returns an array Object[]).

    Integer[] arr = id.getDetails().values().toArray(Integer[]::new);
    

    Collection to int[]

    There's no way convert a Collection of Integer type or an array Integer[] into an array int[] directly. It's not possible to obtain one from another simply by doing casting, these types are not compatible.

    You have to iterate over the source and populate the newly created int[] array. It can be done either "manually" using a loop, or in a more convenient way with streams, the overall approach doesn't change.

    That's how it can be done using Stream API:

    int[] arr = id.getDetails().values().stream() // Stream<Integer> - stream of objects
        .mapToInt(Integer::intValue) // IntStream - stream of primitives
        .toArray();