Issue
I have to store something key value pair:
apple - 001
orange - 001
banana - 001
apple - 002
apple - 003
(sometime key can be duplicate and sometime value can be duplicate. The entire pair won't be duplicate) please suggest perfect data structure in java.
Thanks in advance
Solution
You can use Map<String, Set<String>>
like this.
static void add(Map<String, Set<String>> map, String key, String value) {
map.computeIfAbsent(key, k -> new HashSet<>()).add(value);
}
and
Map<String, Set<String>> map = new HashMap<>();
add(map, "apple", "001");
add(map, "orange", "001");
add(map, "banana", "001");
add(map, "apple", "002");
add(map, "apple", "003");
System.out.println(map);
output:
{banana=[001], orange=[001], apple=[001, 002, 003]}
Answered By - 英語は苦手
Answer Checked By - David Marino (JavaFixing Volunteer)