randomuser1
randomuser1

Reputation: 2803

how can I write elements from my array to my hash map in efficient way in java?

In my java code I have an empty hash map:

private Map<String, String> map = new HashMap<>();

I also have an array of Strings:

String[] array = path.split("/");

This array can be null, empty, or contain from one to three elements. I need to fill up my hash map based on this array, however the keys should be hardcoded - by that I mean that for the first value in the map the key should be one, for the second one it should be two, for the third it should be three. I wrote this algorithm:

if (array == null || array.length == 0){
    LOG.warn("Path is empty");
}
if (array.length == 1){
    map.put("one", array[0]);
} else if (array.length == 2) {
    map.put("one", array[0]);
    map.put("two", array[1]);
} else if (array.length == 3) {
    map.put("one", array[0]);
    map.put("two", array[1]);
    map.put("three", array[2]);
}

but I thought there might be a better (or definitely prettier) way of handling that. Could you please help me with that?

Upvotes: 0

Views: 79

Answers (3)

sfiss
sfiss

Reputation: 2319

As it is tagged with java 8, here you have a streaming answer, even though when accessing indices, the for loop is probably easier to read (very subjective)

String[] numbers = {"one", "two", "three"};
Map<String, String> map = array == null
            ? new HashMap<>()
            : IntStream.range(0, array.length)
                    .mapToObj(Integer::valueOf)
                    .collect(Collectors.toMap(i -> numbers[i], i -> array[i], (i1, i2) -> {
                        throw new RuntimeException();
                    }, LinkedHashMap::new));

Upvotes: 1

Denis Rozhko
Denis Rozhko

Reputation: 70

private static final String[] numNames = {
    "",
    " one",
    " two",
    " three",
    " four",
    " five",
    " six",
    " seven",
    " eight",
    " nine",
    " ten",
    " eleven",
    " twelve",
    " thirteen",
    " fourteen",
    " fifteen",
    " sixteen",
    " seventeen",
    " eighteen",
    " nineteen"
};

private static String[] array = new String[]{"1","2"};

private static Map<String, String> map = new HashMap<>();

public static void main(String[] args) {

    for(int i = 0; i < array.length; i++){
        map.put(numNames[i], array[i]);
    }

}

Upvotes: -1

Tran Ho
Tran Ho

Reputation: 1490

You can check null of the array before this below codes

String[] keys = {"one", "two", "string"};
for(int = 0; i < array.length;i++){
   map.put(keys[i], array[i]);
}

Upvotes: 4

Related Questions