How to subtract a constant value from all elements of an array? [on hold]

  • A+
Category:Languages

I have an array and for example I want to subtract like 7 from all elements of the array. How can I do that except the below logic.

for (int i = 0; i < array.length; i++) {     array[i]-=7; } 

Anything related streams will be helpful.

Edit- It should not necessary be an array. It can be an ArrayList also.

 


With streams you can use map like this :

int[] array = {-1, 8, 9}; array = Arrays.stream(array)         .map(i -> i - 7)         .toArray(); 

or if you are using List you can use :

List<Integer> array = new ArrayList<>(Arrays.asList(-1, 8, 9)); array = array.stream()         .map(i -> i - 7)         .collect(Collectors.toList()); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: