giannisf
giannisf

Reputation: 2599

Map Collections in Java

I am coming from a JavaScript background, and in JS we can map/change an array easily.

var arr = [1,2,3,4];
var doubled = arr.map(function(c) { 
    return c * 2;
});

console.log(doubled); //[2,4,6,8]

Is something like that in Java?

Upvotes: 1

Views: 93

Answers (3)

Nándor Előd Fekete
Nándor Előd Fekete

Reputation: 7108

Definitely:

Integer arr[] = { 1, 2, 3, 4 };
Arrays.stream(arr).map(i -> i * 2).forEach(System.out::println);

Note that this is not changing the original array. It creates a stream out of the source array, creates another stream by applying the map function and executes the println of System.out for each element of the stream.

Use

Integer newArr[] = Arrays.stream(arr)
        .map(i -> i * 2)
        .collect(Collectors.toList())
        .toArray(new Integer[arr.length]);

to collect the elements of the resulting stream into an array of Integers.

EDIT: if you're using primitive types, there's a more efficient way to do it:

int[] intArr = { 1, 2, 3, 4};
int[] newIntArr = Arrays.stream(intArr).map(i -> i * 2).toArray();

Upvotes: 4

SamTebbs33
SamTebbs33

Reputation: 5647

You can do so with a stream.

Integer[] array = {1, 2, 3, 4};
Integer[] doubled = (Integer[]) Arrays.stream(array).map(i -> i * 2).toArray();

The above code will map the original array to a new array where each value is doubled.

Upvotes: 0

flakes
flakes

Reputation: 23654

List<Integer> arr = Arrays.asList(1,2,3,4);
List<Integer> dbl = arr
        .stream()
        .map(a -> a * 2)
        .collect(Collectors.toList());

Upvotes: 0

Related Questions