I'm just barely learning Java and need to accomplish something in Java 8, but I'm struggling to figure out the most efficient way to do it (coming from a PHP background). Essentially I'm trying to give it a regular array, run some calculations, and then save some of those values in a new array where the original key is preserved.
So basically the original array is something like:
0 => 3 1 => 5 2 => 6 3 => 8 and the new array will be an associative array where the keys are specifically assigned like:
1 => 5 3 => 8 In order to help myself visualize it in something I'm more familiar with, I've gotten everything I need working in PHP, and it looks something like this:
$array = array( 8, 3, 2, 9, 1, 15 ); $new_array = array(); foreach ( $array as $key => $value ) { // Calculate something and build new array, for example... if ( 5 > $value ) { $new_value = $value + 5; $new_array[ $key ] = $new_value; } } So in this example, $new_array would be:
1 => 8 2 => 7 4 => 6 I would swear I've seen something where I can do just a basic for loop and access key and value but I can't find where I read that, and everything else I'm finding now talks about iterating through "hash maps" using forEach(), so that seems like the standard approach, but when I try array.forEach((k, v) -> // Calculations.... it tells me that it "cannot find symbol" for array in that context, which is being set immediately prior as int[] array = { // numbers }. As I'm understanding it, I have to convert the array to a hash map in order to be able to use a key/value pair in the foreach, but apparently I'm doing something wrong there as well...
So I guess here are my questions...
- Can I use a basic
forloop for this or I need to convert the array to a hash map in order to access the key/value pairs? How? I don't need to use any specific method, just looking for the most efficient. - I have
import java.util.Arrays;for other reasons - do I need to import something else?
Thanks for your help.
UPDATE -------------------------
To clarify, I'll need to do something similar later in the code again using $new_array as the source, so I need to be able to get the keys and not just the iteration count.
So for example if I were to wrap the foreach in a while loop, where the first time it starts with $array and each subsequent time it sets $array as $new_array to run the calculations again.
So in other words, I can't rely on the iteration count to match the keys.
forloop and store the result in a Map using the index variable as the key.$new_arraythough, so the counter won't match the keys. Is there a way to specifically get the key value?