Name - Code (String)
A - 123
B - 123
C - 23
D - 123
E - 23
F - 23
G - 66
H - 66
What's the best data structure to represent this data. Names should be able to iterate easily.
Edit
Names are unique.
What's needed to be done is something like this.
Had doubts in using Hashmap that why I asked.
Code is a STRING
for( loop dataStructure names (lets say n)){
if(NAME.equals(n){
String code = dataStructure.get(n);
do somthing
}
}
If the names are unique, a HashMap woulrd be apropriate.
You can iterate over the keys with keys().
To iterate over the entries you can iterate over the entrySet().
See the JavaDoc of Map
If you need to perform a reverse lookup you could use the BiMap from Guava. (General a very good library)
Map entries example:
public final class MapExample {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("A", "123");
for (Map.Entry<String, String> mapEntry : map.entrySet()) {
if (mapEntry.getKey().equals("A")) {
final String code = mapEntry.getValue();
System.out.println("Your desired code: " + code);
}
}
}
}
But since NAME seems to be a constant, you could simple do String code = map.get(NAME)?
I thinks you are considering this:
public enum Code {
A("123"),
B("123"),
C("23"),
D("123"),
E("23"),
F("23"),
G("66"),
H("66");
final public String value;
Code(String value) {
this.value = value;
}
}
String h = Code.H.value;
for (Code code : Code.values()) {
System.out.printf("Name %s, code %s%n", code, code.value);
}
Sounds like a Map. Specifically, if the order of the names is important, you can use a TreeMap.
You can populate it with the put method, and then iterate over the entries (or just the keys, or just the values):
// Fill the map:
Map<String, String> map = new TreeMap<>();
map.put("A", "123");
map.put("B", "123");
// etc...
// Iterate over it:
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.pritnln ("Key: " + entry.getKey() + " value: " + entry.getValue());
}
EDIT:
If the order is not important, as noted in later edits to the OP, a HashMap would do just fine.
Note, however, that if you're looking for a specific key, like stated in the example in the OP, there's no point in looping over the keys - you just need to use get or containsKey:
String name = ...;
String code = map.get(name);
if (code != null) {
// do something...
}
I would suggest go for HashMap
The HashMap class uses a hashtable to implement the Map interface.
This allows the execution time of basic operations, such as get( )
and put( ), to remain constant even for large sets
HashMap are efficient for locating a value based on a key and
inserting and deleting values based on a key. The entries of a
HashMap are not ordered.
import java.util.HashMap;
import java.util.Set;
public class MyHashMapRead {
public static void main(String a[]){
HashMap<String, Integer> hm = new HashMap<String, Integer>();
//add key-value pair to hashmap
hm.put("A", "1");
hm.put("B", "2");
hm.put("C","3");
System.out.println(hm);
Set<String> keys = hm.keySet();
for(String key: keys){
System.out.println("Value of "+key+" is: "+hm.get(key));
}
}
}
Related
I have a structure like below ,
Key: active-csr-HA-profile & Value: {sapd-outside=[outside], sapd-extra4=[extra4], sapd-extra3=[extra3], sapd-inside=[inside]}
Key = sapd-outside, Value = [outside]
Key = sapd-extra4, Value = [extra4]
Key = sapd-extra3, Value = [extra3]
Key = sapd-inside, Value = [inside]
Key: standby-csr-HA-profile & Value: {sapd-outside=[outside], sapd-extra4=[extra4], sapd-extra3=[extra3], sapd-inside=[inside]}
Key = sapd-outside, Value = [outside]
Key = sapd-extra4, Value = [extra4]
Key = sapd-extra3, Value = [extra3]
Key = sapd-inside, Value = [inside]
the above if of format Hashtable<String, Map<String, Set<String>>>
I want to compare if sapd-outside of active-csr-HA-profile is same as one of the keys of standby-csr-HA-profile. So compare each key of active-csr-HA-profile to each key of standby-csr-HA-profile.
I looked some similar questions but what i am working out is not solving the purpose.
As already mentioned in the comments, the Hashtable is considered obsolete. Its replacement is HashMap. If you wish make HashMap synchronized the same way the Hashtable does, use the Collections::synchronizedMap decorator on it.
The structure of your Hashtable looks a bit unclear. I guess the following structure matches your one the best and I base my solution on it.
Hashtable<String, Map<String, Set<String>>> map = new Hashtable<>();
Map<String, Set<String>> activeCsrHAProfile = new HashMap<>();
activeCsrHAProfile.put("sapd-outside", new HashSet<>(Arrays.asList("outside")));
activeCsrHAProfile.put("sapd-extra4", new HashSet<>(Arrays.asList("extra4")));
activeCsrHAProfile.put("sapd-extra3", new HashSet<>(Arrays.asList("extra3")));
activeCsrHAProfile.put("sapd-inside", new HashSet<>(Arrays.asList("inside")));
Map<String, Set<String>> standbyCsrHAProfile = new HashMap<>();
standbyCsrHAProfile.put("sapd-outside", new HashSet<>(Arrays.asList("outside")));
standbyCsrHAProfile.put("sapd-extra4", new HashSet<>(Arrays.asList("extra4")));
standbyCsrHAProfile.put("sapd-extra3", new HashSet<>(Arrays.asList("extra3")));
standbyCsrHAProfile.put("sapd-inside", new HashSet<>(Arrays.asList("inside")));
map.put("active-csr-HA-profile", activeCsrHAProfile);
map.put("standby-csr-HA-profile", standbyCsrHAProfile);
In case my structure differs a bit from yours, there would be no problem to amend the solution in order to match your structure - the principle is the same.
Set<String> sapdOutsideOfActiveCsrHAProfile = map.get("active-csr-HA-profile")
.get("sapd-outside");
map.get("standby-csr-HA-profile").entrySet()
.stream()
.filter(i -> i.getValue().containsAll(sapdOutsideOfActiveCsrHAProfile))
.forEach(e -> System.out.println("Found at: " +
"key=" + e.getKey() + ", value=" + e.getValue()));
.filter(i -> i.getValue().containsAll(..) filters those entris which values Set<String> contains all of the required Strings.
.forEach(..) gives a consumer performing an action over all the matching results.
In case you need the boolean representing whether the match has occurred or not, do:
boolean matches = map.get(..).entrySet().stream().filter(..).findFirst().isPresent();
As mentioned in the comments, HashTable is a debatable choice. Regardless of the implementation you choose, you could create your own class to manage the messy stuff:
public class CustomMap extends Hashtable<String, Map<String, Set<String>>> {
public CustomMap() {
super();
}
public boolean compareEntries(String key1, String key2) {
if (!this.containsKey(key1) || !this.containsKey(key2) || this.get(key1).size() != this.get(key2).size())
return false;
for (String innerKey : this.get(key1).keySet()) {
if (!this.get(key2).containsKey(innerKey)) {
return false;
}
final Set<String> setA = this.get(key1).get(innerKey);
final Set<String> setB = this.get(key2).get(innerKey);
if (!setA.containsAll(setB) || !setB.containsAll(setA)) {
return false;
}
}
return true;
}
}
I took the assumption there could be more entries in your table and you'd want to compare specific entries.
You can iterate through a map with its entry set:
Hashtable<String, Map<String, Set<String>>> table = new Hashtable();
for (Map.Entry<String, Map<String, Set<String>>> entry : table.entrySet()) {
String key = entry.getKey();
Map<String, Set<String>> map = entry.getValue();
for (Map.Entry<String, Set<String>> mapEntry : map.entrySet()) {
String mapKey = mapEntry.getKey();
Set<String> set = mapEntry.getValue();
for (String text : set) {
// ...
}
}
}
Nesting sets inside maps inside maps makes the code hard to read though, you might want to use specialized objects instead.
As others have said, in most cases HashMap is preferrable compared to an Hashtable.
I have a HashMap as follows-
HashMap<String, Integer> BC = new HashMap<String, Integer>();
which stores as keys- "tokens/tages" and as values- "frequency of each tokens/tags".
Example-
"the/at" 153
"that/cs" 45
"Ann/np" 3
I now parse through each key and check whether for same token say "the" whether it's associated with more than one tag and then take the largest of the two.
Example-
"the/at" 153
"the/det" 80
Then I take the key- "the/at" with value - 153.
The code that I have written to do so is as follows-
private HashMap<String, Integer> Unigram_Tagger = new HashMap<String, Integer>();
for(String curr_key: BC.keySet())
{
for(String next_key: BC.keySet())
{
if(curr_key.equals(next_key))
continue;
else
{
String[] split_key_curr_key = curr_key.split("/");
String[] split_key_next_key = next_key.split("/");
//out.println("CK- " + curr_key + ", NK- " + next_key);
if(split_key_curr_key[0].equals(split_key_next_key[0]))
{
int ck_v = 0, nk_v = 0;
ck_v = BC.get(curr_key);
nk_v = BC.get(next_key);
if(ck_v > nk_v)
Unigram_Tagger.put(curr_key, BC.get(curr_key));
else
Unigram_Tagger.put(next_key, BC.get(next_key));
}
}
}
}
But this code is taking too long to compute since the original HashMap 'BC' has 68442 entries which comes approximately to its square = 4684307364 times (plus some more).
My question is this- can I accomplish the same output using a more efficient method?
Thanks!
Create a new
Map<String,Integer> highCount = new HashMap<>();
that will map tokens to their largest count.
Make a single pass through the keys.
Split each key into its component tokens.
For each token, look in highMap. If the key does not exist, add it with its count. If the entry already exists and the current count is greater than the previous maximum, replace the maximum in the map.
When you are done with the single pass the highCount will contain all the unique tokens along with the highest count seen for each token.
Note: This answer is intended to give you a starting point from which to develop a complete solution. The key concept is that you create and populate a new map from token to some "value" type (not necessarily just Integer) that provides you with the functionality you need. Most likely the value type will be a new custom class that stores the tag and the count.
The slowest part of your current method is due to the pairwise comparison of keys. First, define a Tuple class:
public class Tuple<X, Y> {
public final X x;
public final Y y;
public Tuple(X x, Y y) {
this.x = x;
this.y = y;
}
}
Thus you can try an algorithm that does:
Initializes a new HashMap<String, Tuple<String, Integer>> result
Given input pair (key, value) from the old map, where key = "a/b", check whether result.keySet().contains(a) and result.keySet().contains(b).
If both a and b is not present, result.put(a, new Tuple<String, Integer>(b, value) and result.put(b, new Tuple<String, Integer>(a, value))
If a is present, compare value and v = result.get(a). If value > v, remove a and b from result and do step 3. Do the same for b. Otherwise, get the next key-value pair.
After you have iterated through the old hash map and inserted everything, then you can easily reconstruct the output you want by transforming the key-values in result.
A basic thought on the algorithm:
You should get the entrySet() of the HashMap and convert it to a List:
ArrayList<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
Now you should sort the list by the keys in alphabetical order. We do that because the HashMap has no order, so you can expect that the corresponding keys might be far apart. But by sorting them, all related keys are directly next to each other.
Collections.sort(list, Comparator.comparing(e -> e.getKey()));
The entries "the/at" and "the/det" will be next to each other, thanks to sorting alphabetically.
Now you can iterate over the entire list while remembering the best item, until you find a better one or you find the first item which has not the same prefix (e.g. "the").
ArrayList<Map.Entry<String, Integer>> bestList = new ArrayList<>();
// The first entry of the list is considered the currently best item for it's group
Map.Entry<String, Integer> currentBest = best.get(0);
String key = currentBest.getKey();
String currentPrefix = key.substring(0, key.indexOf('/'));
for (int i=1; i<list.size(); i++) {
// The item we compare the current best with
Map.Entry<String, Integer> next = list.get(i);
String nkey = next.getKey();
String nextPrefix = nkey.substring(0, nkey.indexOf('/'));
// If both items have the same prefix, then we want to keep the best one
// as the current best item
if (currentPrefix.equals(nextPrefix)) {
if (currentBest.getValue() < next.getValue()) {
currentBest = next;
}
// If the prefix is different we add the current best to the best list and
// consider the current item the best one for the next group
} else {
bestList.add(currentBest);
currentBest = next;
currentPrefix = nextPrefix;
}
}
// The last one must be added here, or we would forget it
bestList.add(currentBest);
Now you should have a list of Map.Entry objects representing the desired entries. The complexity should be n(log n) and is limited by the sorting algorithm, while grouping/collection the items has a complexity of n.
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class Point {
public static void main(String[] args) {
HashMap<String, Integer> BC = new HashMap<>();
//some random values
BC.put("the/at",5);
BC.put("Ann/npe",6);
BC.put("the/atx",7);
BC.put("that/cs",8);
BC.put("the/aty",9);
BC.put("Ann/np",1);
BC.put("Ann/npq",2);
BC.put("the/atz",3);
BC.put("Ann/npz",4);
BC.put("the/atq",0);
BC.put("the/atw",12);
BC.put("that/cs",14);
BC.put("that/cs1",16);
BC.put("the/at1",18);
BC.put("the/at2",100);
BC.put("the/at3",123);
BC.put("that/det",153);
BC.put("xyx",123);
BC.put("xyx/w",2);
System.out.println("\nUnsorted Map......");
printMap(BC);
System.out.println("\nSorted Map......By Key");
//sort original map using TreeMap, it will sort the Map by keys automatically.
Map<String, Integer> sortedBC = new TreeMap<>(BC);
printMap(sortedBC);
// find all distinct prefixes by spliting the keys at "/"
List<String> uniquePrefixes = sortedBC.keySet().stream().map(i->i.split("/")[0]).distinct().collect(Collectors.toList());
System.out.println("\nuniquePrefixes: "+uniquePrefixes);
TreeMap<String,Integer> mapOfMaxValues = new TreeMap<>();
// for each prefix from the list above filter the entries from the sorted map
// having keys starting with this prefix
//and sort them by value in descending order and get the first which will have the highst value
uniquePrefixes.stream().forEach(i->{
Entry <String,Integer> e =
sortedBC.entrySet().stream().filter(j->j.getKey().startsWith(i))
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).findFirst().get();
mapOfMaxValues.put(e.getKey(), e.getValue());
});
System.out.println("\nmapOfMaxValues...\n");
printMap(mapOfMaxValues);
}
//pretty print a map
public static <K, V> void printMap(Map<K, V> map) {
map.entrySet().stream().forEach((entry) -> {
System.out.println("Key : " + entry.getKey()
+ " Value : " + entry.getValue());
});
}
}
// note: only tested with random values provided in the code
// behavior for large maps untested
I have a nested HashMap:
HashMap<String, Map<String,Integer>> map = new HashMap<>();
The key for the nested map may have multiple values:
{Color={Red=4, Blue=6}}
I want to be able to return the key of the nested map that has the lowest value. In this case, if I gave the key Color from the outer map, I want to have Red returned.
Any help is greatly appreciated.
Get the inner map by key.
Get the Iterator of the inner map.
Assign the first kvp as the minimum.
Loop through the iterator checking if any subsequent kvp is less than the minimum and assign it if true.
Return the minimum's key.
Code Sample:
public static void main(String[] args) throws Exception {
Map<String, Map<String,Integer>> map = new HashMap() {{
put("Color", new HashMap() {{
put("Red", 4);
put("Orange", 1);
put("Blue", 6);
put("Yellow", 2);
}});
}};
System.out.println(getInnerKeyWithLowestValue(map, "Color"));
}
public static String getInnerKeyWithLowestValue(Map<String, Map<String,Integer>> map, String outerKey) {
Map<String, Integer> innerMap = map.get(outerKey);
// Make sure inner map was retrieved
if (innerMap != null) {
Iterator<Map.Entry<String,Integer>> it = innerMap.entrySet().iterator();
Map.Entry<String, Integer> minimum = it.next();
while (it.hasNext()) {
Map.Entry<String, Integer> next = it.next();
if (next.getValue() < minimum.getValue()) {
minimum = next;
}
}
return minimum.getKey();
}
return ""; // Inner map doesn't exist
}
Results:
Orange
If Java 8 is a option for you, it is easy to write a very concise method to do that:
public static String lowestValueKey(Map<String, Map<String, Integer>> map, String key) {
return map.get(key).entrySet().stream()
.min(Comparator.comparing(Map.Entry::getValue))
.get().getKey();
}
Also using Maps inside Maps can be very tedious sometimes. You may consider using Table<String, String, Integer> from Guava library.
Get the Hashmap from the inner hashmap and sort the hashmap based on the value which is shown in the link enter link description here. Obviously firs entry will be the lowest value in your innerhashmap.
I have an homework to do, so I have finished the script but the problem is with the values.
The main code is (I cannot change it due to homework) :
List<String> result = cw.getResult();
for (String wordRes : result) {
System.out.println(wordRes);
}
It have to return:
abc 2
def 2
ghi 1
I have no idea how to handle that.
Now only shows:
abc
def
ghi
I have no idea how to change this method getResult to return with the value of the hashmap as well without changing the first main code.
public List<String> getResult() {
List<String> keyList = new ArrayList<String>(list.keySet());
return keyList;
}
The hashmap is: {abc=2, def=2, ghi=1}
And list: Map<String, Integer> list = new HashMap<String, Integer>();
Please help me if you know any resolution.
I think that now that you have learned about keySet and valueSet, your next task is to learn about entrySet. That's a collection of Map.Entry<K,V> items, which are in turn composed of the key and the value.
That's precisely what you need to complete your task - simply iterate over the entrySet of your Map while adding a concatenation of the value and the key to your result list:
result.add(entry.getKey() + " " + entry.getValue());
Note that if you use a regular HashMap, the items in the result would not be arranged in any particular order.
You need to change this line:
List<String> keyList = new ArrayList<String>(list.keySet());
to:
//first create the new List
List<String> keyList = new List<String>();
//iterate through the map and insert the key + ' ' + value as text
foreach(string item in list.keySet())
{
keyList.add(item+' '+list[item]);
}
return keyList;
I haven't written java in a while so compiler errors might appear, but the idea should work
Well simplest way make an ArrayList and add as #dasblinkenlight said...
Iterator<?> it = list.entrySet().iterator();
while (it.hasNext()) {
#SuppressWarnings("rawtypes")
Map.Entry maps = (Map.Entry) it.next();
lista.add(maps.getKey() + " " + maps.getValue());
}
}
public List<String> getResult() {
List<String> temp = lista;
return temp;
}
If you want to iterate over map entries in order of keys, use an ordered map:
Map<String, Integer> map = new TreeMap<String, Integer>();
Then add your entries, and to print:
for (Map.Entry<String, Ibteger> entry : map.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
This question already has answers here:
How do I efficiently iterate over each entry in a Java Map?
(46 answers)
Closed 7 years ago.
I have this field:
HashMap<String, HashMap> selects = new HashMap<String, HashMap>();
For each Hash<String, HashMap> I need to create a ComboBox, whose items are the value (which happens to be a HashMap itself) of HashMap <String, **HashMap**>.
By way of (non-functioning) demonstration:
for (int i=0; i < selects.size(); i++) {
HashMap h = selects[i].getValue();
ComboBox cb = new ComboBox();
for (int y=0; y < h.size(); i++) {
cb.items.add(h[y].getValue);
}
}
I know I'm a bit late for that one, but I'll share what I did too, in case it helps someone else :
HashMap<String, HashMap> selects = new HashMap<String, HashMap>();
for(Map.Entry<String, HashMap> entry : selects.entrySet()) {
String key = entry.getKey();
HashMap value = entry.getValue();
// do what you have to do here
// In your case, another loop.
}
Lambda Expression Java 8
In Java 1.8 (Java 8) this has become lot easier by using forEach method from Aggregate operations(Stream operations) that looks similar to iterators from Iterable Interface.
Just copy paste below statement to your code and rename the HashMap variable from hm to your HashMap variable to print out key-value pair.
HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>();
/*
* Logic to put the Key,Value pair in your HashMap hm
*/
// Print the key value pair in one line.
hm.forEach((k,v) -> System.out.println("key: "+k+" value:"+v));
Here is an example where a Lambda Expression is used:
HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>();
Random rand = new Random(47);
int i=0;
while(i<5){
i++;
int key = rand.nextInt(20);
int value = rand.nextInt(50);
System.out.println("Inserting key: "+key+" Value: "+value);
Integer imap =hm.put(key,value);
if( imap == null){
System.out.println("Inserted");
}
else{
System.out.println("Replaced with "+imap);
}
}
hm.forEach((k,v) -> System.out.println("key: "+k+" value:"+v));
Output:
Inserting key: 18 Value: 5
Inserted
Inserting key: 13 Value: 11
Inserted
Inserting key: 1 Value: 29
Inserted
Inserting key: 8 Value: 0
Inserted
Inserting key: 2 Value: 7
Inserted
key: 1 value:29
key: 18 value:5
key: 2 value:7
key: 8 value:0
key: 13 value:11
Also one can use Spliterator for the same.
Spliterator sit = hm.entrySet().spliterator();
UPDATE
Including documentation links to Oracle Docs.
For more on Lambda go to this link and must read Aggregate Operations and for Spliterator go to this link.
Map.values():
HashMap<String, HashMap<SomeInnerKeyType, String>> selects =
new HashMap<String, HashMap<SomeInnerKeyType, String>>();
...
for(HashMap<SomeInnerKeyType, String> h : selects.values())
{
ComboBox cb = new ComboBox();
for(String s : h.values())
{
cb.items.add(s);
}
}
Streams Java 8
Along with forEach method that accepts a lambda expression we have also got stream APIs, in Java 8.
Iterate over entries (Using forEach and Streams):
sample.forEach((k,v) -> System.out.println(k + "=" + v));
sample.entrySet().stream().forEachOrdered((entry) -> {
Object currentKey = entry.getKey();
Object currentValue = entry.getValue();
System.out.println(currentKey + "=" + currentValue);
});
sample.entrySet().parallelStream().forEach((entry) -> {
Object currentKey = entry.getKey();
Object currentValue = entry.getValue();
System.out.println(currentKey + "=" + currentValue);
});
The advantage with streams is they can be parallelized easily and can be useful when we have multiple CPUs at disposal. We simply need to use parallelStream() in place of stream() above. With parallel streams it makes more sense to use forEach as forEachOrdered would make no difference in performance. If we want to iterate over keys we can use sample.keySet() and for values sample.values().
Why forEachOrdered and not forEach with streams ?
Streams also provide forEach method but the behaviour of forEach is explicitly nondeterministic where as the forEachOrdered performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order. So forEach does not guarantee that the order would be kept. Also check this for more.
You can iterate over a HashMap (and many other collections) using an iterator, e.g.:
HashMap<T,U> map = new HashMap<T,U>();
...
Iterator it = map.values().iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
I generally do the same as cx42net, but I don't explicitly create an Entry.
HashMap<String, HashMap> selects = new HashMap<String, HashMap>();
for (String key : selects.keySet())
{
HashMap<innerKey, String> boxHolder = selects.get(key);
ComboBox cb = new ComboBox();
for (InnerKey innerKey : boxHolder.keySet())
{
cb.items.add(boxHolder.get(innerKey));
}
}
This just seems the most intuitive to me, I think I'm prejudiced against iterating over the values of a map.
Use entrySet,
/**
*Output:
D: 99.22
A: 3434.34
C: 1378.0
B: 123.22
E: -19.08
B's new balance: 1123.22
*/
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class MainClass {
public static void main(String args[]) {
HashMap<String, Double> hm = new HashMap<String, Double>();
hm.put("A", new Double(3434.34));
hm.put("B", new Double(123.22));
hm.put("C", new Double(1378.00));
hm.put("D", new Double(99.22));
hm.put("E", new Double(-19.08));
Set<Map.Entry<String, Double>> set = hm.entrySet();
for (Map.Entry<String, Double> me : set) {
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
double balance = hm.get("B");
hm.put("B", balance + 1000);
System.out.println("B's new balance: " + hm.get("B"));
}
}
see complete example here:
http://www.java2s.com/Code/JavaAPI/java.util/HashMapentrySet.htm