The Easiest Way to Transform Collection to Array

The easiest way to transform collection to array?

Where x is the collection:

Foo[] foos = x.toArray(new Foo[x.size()]);

laravel collection to array

You can use toArray() of eloquent as below.

The toArray method converts the collection into a plain PHP array. If the collection's values are Eloquent models, the models will also be converted to arrays

$comments_collection = $post->comments()->get()->toArray()

From Laravel Docs:

toArray also converts all of the collection's nested objects that are an instance of Arrayable to an array. If you want to get the raw underlying array, use the all method instead.

Convert Collection to int[] array

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

How to convert a collection to an array in javascript

You can do this:

var coll = document.getElementsByTagName('div');

var arr = Array.prototype.slice.call( coll, 0 );

EDIT: As @Chris Nielsen noted, this fails in IE pre-9. Best would be to do some feature testing, and create a function that can handle either, or just do a loop as in the (second) solution from @brilliand.

Quick way to convert a Collection to Array or List?

The reason that all BCL collection classes hide their inner array is for reasons of "API niceness". The internal array can change in case it needs to grow or shrink. Then, any user code that has a reference to the old array can become confused. Also, user code might access array indexes that are invalid to access on the collection. If you have a List with Capacity = 16 && Count == 10 and then you can access the internal array at index 15 which the list would not normally allow.

These issues make the API hard to use. They cause support tickets and Stack Overflow questions.

Delete your existing code and replace it with:

TreeNodeCollection nodes;
var myArray = nodes.Cast<TreeNode>().ToArray();

You can make this into an extension method if you feel the need for that. Type the parameter as IEnumerable (no generics). It is a mystery to me why the existing collections in the BCL have not been upgraded to implement IEnumerable<T>. That's why you need the Cast. I just created a User Voice item for this.

How to convert a Java 8 Stream to an Array?

The easiest method is to use the toArray(IntFunction<A[]> generator) method with an array constructor reference. This is suggested in the API documentation for the method.

String[] stringArray = stringStream.toArray(String[]::new);

What it does is find a method that takes in an integer (the size) as argument, and returns a String[], which is exactly what (one of the overloads of) new String[] does.

You could also write your own IntFunction:

Stream<String> stringStream = ...;
String[] stringArray = stringStream.toArray(size -> new String[size]);

The purpose of the IntFunction<A[]> generator is to convert an integer, the size of the array, to a new array.

Example code:

Stream<String> stringStream = Stream.of("a", "b", "c");
String[] stringArray = stringStream.toArray(size -> new String[size]);
Arrays.stream(stringArray).forEach(System.out::println);

Prints:

a
b
c

Converting VBA Collection to Array

It's all there, you're just not using the Function as a function. You need to store the result in something, like 'NewArray'..?

Public col As New Collection
Public Sub Test()
For Each ws In ThisWorkbook.Worksheets
If InStr(ws.Name, "Template") <> 0 Then
col.Add ws.Name
End If
Next ws

' Tweaked as per Vityata's comment

If col.Count > 0 Then
newarray = collectionToArray(col)
Else
' Do something else
End If

End Sub

Function collectionToArray(c As Collection) As Variant()
Dim a() As Variant: ReDim a(0 To c.Count - 1)
Dim i As Integer
For i = 1 To c.Count
a(i - 1) = c.Item(i)
Next
collectionToArray = a
End Function

How do I convert this collection to an array in Laravel 5.2

You need to use ->toArray() method:

$directories = DirectoryModel::lists('name', 'id')->toArray();

By the way:

The lists method on the Collection, query builder and Eloquent query builder objects has been renamed to pluck. The method signature remains the same.

So you better use pluck instead of lists, it's deprecated:

$directories = DirectoryModel::pluck('name', 'id')->toArray();

Upgrade Guide

What is the best way of converting ListLong object to long[] array in java?

Since Java 8, you can do the following:

long[] result = values.stream().mapToLong(l -> l).toArray();

What's happening here?

  1. We convert the List<Long> into a Stream<Long>.
  2. We call mapToLong on it to get a LongStream
    • The argument to mapToLong is a ToLongFunction, which has a long as the result type.
    • Because Java automatically unboxes a Long to a long, writing l -> l as the lambda expression works. The Long is converted to a long there. We could also be more explicit and use Long::longValue instead.
  3. We call toArray, which returns a long[]


Related Topics



Leave a reply



Submit