2

I have two String arrays of the same size.

I need to make a Map with name and value. How do I add them to the Map?

String[] labelNames = request.getParameterValues("labelName");
String[] labelValues = request.getParameterValues("labelValues");
Map<String,String> labels = new HashMap<>();
aUserHimself
  • 1,589
  • 2
  • 17
  • 26

5 Answers5

2

You have arrays of same size, so you can iterate over them with the same for-loop, you'll access same index on both and put them into the map :

for(int i=0; i<labelNames.length; i++){
    labels.put(labelNames[i], labelValues [i]);
}
azro
  • 53,056
  • 7
  • 34
  • 70
2

If you got 2 arrays where the size is the same just make a for-loop which uses the labelName and the labelValue

for(int i = 0; i < labelNames.length; i++) {
    labels.put(labelNames[i], labelValues[i]);
}

if you're not sure if the size of the two arrays is the same add this check before the loop:

if(labelNames.length == labelValues.length) {...}
CodeMatrix
  • 2,124
  • 1
  • 18
  • 30
1

A solution for Java 7 - you can use the for loop structure with a single index to advance into the 2 arrays at the same time.

As for the assumption labelNames.length == labelValues.length it is usually better to always check it to make sure you didn't introduce a bug and get unexpected results:

if(labelNames.length == labelValues.length) {
    int i;
    for(i = 0; i < labelNames.length; i++) {
        labels.put(labelNames[i], labelValues[i]);
    }
}

In Java 8 you could use Streams as an alternative:

Map<String, String> map =
        IntStream.range(0, names.length)
                .boxed()
                .collect(Collectors.toMap(i -> labelNames[i], i -> labelValues[i]));
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
aUserHimself
  • 1,589
  • 2
  • 17
  • 26
1

use this code :

Map<String,String> labels = new HashMap<>();
for(int i=0;i<labelNames.length;i++)
    labels.put(labelNames[i] , labelValues[i]);
Ali Faris
  • 17,754
  • 10
  • 45
  • 70
1

First of all:

 Map<String,String> labels = new HashMap<String, String>();

and then:

for (int i=0; i < labelNames.length; i++) 
{
  labels.put(labelNames[i], labelValues[i]);
}
Flocke
  • 764
  • 6
  • 14