Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a JavaScript style Collection in Java

In JavaScript I can define the following collection with keys awaiting values

var items = {
                'book':null,
                'pen':null,
                'pencil':null,
                'chicken':null,
                'wallet':null
            };

Then when I am ready to add values to my collection, I can do for instance

for(var p in items){
  if(some condition){
     items[p]=someValue;
  }
}

Is there a way to do this with the same level of efficiency in java?

I know that in old Java I can combine a Map and a List to accomplish this, but are their new data structures in Java that can handle this? I am talking about Java 7 (or 8) perhaps? I am using Google App-Engine for my Java.

like image 667
Katedral Pillon Avatar asked Sep 21 '26 05:09

Katedral Pillon


2 Answers

You could try it this way, if you're looking for the same style.

 HashMap<String, String > items  = new HashMap<String, String>(){{
        put("book",null);
        put("pen",null);
    }};

Later you can put again with keys.

items.put("book", "Some Bible");

It seems you are new to Java and both Collections. I'm highly recommend you to read the about HashMap more before proceeding.

like image 147
Suresh Atta Avatar answered Sep 22 '26 19:09

Suresh Atta


EDIT: Updated my answer based on the latest comments.

You could perfectly use a HashMap to achieve the same effect. To iterate over the existing keys, use the Map#keySet method.

Map<String, String> map = new HashMap<String, String>();
map.put("book", null);
map.put("pen", null);

for (String key : map.keySet()) {
    map.put(key, "Some Value");
}

System.out.println(map);
like image 42
xaviert Avatar answered Sep 22 '26 19:09

xaviert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!