Java Collection: Map Interface - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

demo-image

Java Collection: Map Interface

Share This

A Map contains values on the basis of keys. Each key and value pair is known as an entry. It contains only unique keys. But it can contain duplicate values.

Note that a Map can't be traversed so you need to convert it into Set using keySet() or entrySet() method.

Source code of Item.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.t4b.test;
public class Item {
String name;
int id;
double price;
public Item(String name, int id, double price) {
super();
this.name = name;
this.id = id;
this.price = price;
}
@Override
public String toString() {
return "Item [name=" + name + ", id=" + id + ", price=" + price + "]";
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Source code of TestMain.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.t4b.test;
import java.util.HashMap;
import java.util.Map;
public class TestMain {
public static void main(String[] args) {
Map<Integer, Item> map = new HashMap<Integer, Item>();
map.put(1, new Item("Apple", 1, 150.0));
map.put(2, new Item("Grape", 2, 250.0));
map.put(3, new Item("Mango", 3, 10));
map.put(2, new Item("Pine Apple", 4, 100));
for (Map.Entry<Integer, Item> item : map.entrySet()) {
System.out.println(item.getKey() + " : " + item.getValue());
}
map.remove(2);
map.replace(1, new Item("Apple", 1, 220.0));
for (Map.Entry<Integer, Item> item : map.entrySet()) {
System.out.println(item.getKey() + " : " + item.getValue());
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX


Happy Exploring!

Comment Using!!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.