Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am working on a personal project on Java. I have a Map called allow and the second parameter is another Map. I am trying to compare the second parameter of the Map inside allow. If anyone can help me that would be a big help.
public boolean checkBank(String bank, int cNumber){
Map <String, Map<String, String> > allow = new HashMap<>();
String num = Integer.toString(cNumber);
Iterator<Map.Entry<String, Map<String, String>>> entries = allow.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, Map<String, String>> entry = entries.next();
if (entry.getKey().equals(bank)) {
String all = entry .getValue().get(0);
for (int i = 0; i < entry.getValue().size(); i++) {
if(entry.getValue().equals(num)) {
return true;
}
}
}
}
return false;
}
On the statement: if(entry.getValue().equals(num))
entry.getValue() is a Map, but num is a string. These two are not compatible types, so they can never be equal.
It's worth noting that you are looking for the one entry with the key value equal to bank. Rather than scan through all Map.Entry objects for the one which has the right value, why not just use the statement:
Map<String,String> map = allow.get(bank);
Let the outer map do this work for you.
Your question didn't exactly make clear what you wanted, but I'm guessing that you either want to look, in the inner Map, for an Entry where either the key or the value matches num. You can do that with either
map.containsKey(num)
or
map.containsValue(num)
Is that basically what you are looking for?
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm implementing a bag of Integers in java and I'm not sure how to do so. I would like to do so with either a HashMap, LinkedHashMap, TreeMap, TreeSet, or HashSet. Some of the things I'd like to do are
Be able to count the number of occurrences of a certain element (So I cannot use a set)
be able to add without the structure immediately deleting duplicate integers
I've tried implementing a map so far but I run into problems when I try to add to the map because I'm trying to implement a bag of integer objects not key value pairs.
public class Bag<Integer> {
private int count = 0;
private HashMap <T, Integer> map;
//class constructor
public Bag(){
this.map = new HashMap <T, Integer>();
}
would a linked hash set be best? I'd like to add duplicate Integers.
If I read your question correctly, you simply want
Map<Integer, Integer> integerBag = new HashMap<>();
Key: represents the different Integers you have in your bag.
Value: represents the count how often the corresponding key was added.
When adding a "new" Integer, you put(newValue, 1) into the map. When the same number comes in, you increase that counter; and decrease on removal.
Beyond that:
without the structure immediately deleting duplicate integers doesn't make much sense. Integers are just numbers; why would you want to remember "6 6 6" ... when you could remember "I got 6 three times" instead?!
Given your comments:
you don't need to change the signature of your method. The compiler generates code to turn primitive types such as int into their big brothers such as Integer automatically. That is called auto-boxing.
but you can also do that manually.
See here:
int intval =5;
Integer asInteger = Integer.valueOf(intval);
if (Integer bag.contains(asInteger)) {
Just use a HashMap. You might want to count how many duplicates you have:
Map<Whatever, Long> bag = new HashMap<>();
To add an element, use the merge method:
bag.merge(someElement, 1, (oldValue, value) -> oldValue + 1);
And to remove an element, you might want to use the computeIfPresent method:
bag.computeIfPresent(someElement, (key, value) -> (value == 1 ? null : value - 1));
Because of your requirement #2, I don't think you can use any collection based on hashing. If you need to retain duplicate Integers, you'll need to use a List.
Adding a new items is easy, just call add() on the list. Finding all items requires a short loop; to count them just call size() on the resulting list.
The code below is not tested.
public class Bag<T> {
private List<T> items = new ArrayList<>();
public void add( T i ) { items.add(i); }
public List<T> findAll( T target ) {
ArrayList<T> retVal = new ArrayList<>();
for( T i : items ) {
if( i.equals(target) )
retVal.add( i );
}
return retVal;
}
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I have the below Java code excert. I am expecting to see the keys printed in a sorted manner (since I am using a TreeMap), but it is not sorting the keys. What I am missing?
CODE:
public class TreeMapTest {
static TreeMap<String,String> li=new TreeMap<String,String>();
static void readAndPrint(){
for (Map.Entry<String, String> entry:li.entrySet() ){
System.out.println(entry);
}
}
public static void main(String[] args) {
for (int i=0;i<10;i++){
String key = String.valueOf(new Random().nextInt(100));
String item = UUID.randomUUID().toString().substring(30);
li.put(key,item);
System.out.println(MessageFormat.format("inserting ({0},{1})",key,item));
}
readAndPrint();
}
}
Sample output:
inserting (7,f4b66a)
inserting (2,5f417d)
inserting (51,90bb9f)
inserting (99,4bfb73)
inserting (41,a4e9d5)
inserting (14,9286d6)
inserting (44,ec4fbd)
inserting (58,e7dd3a)
inserting (69,c54e66)
inserting (0,d1fbfe)
0=d1fbfe
14=9286d6
2=5f417d
41=a4e9d5
44=ec4fbd
51=90bb9f
58=e7dd3a
69=c54e66
7=f4b66a
99=4bfb73
As you see I am not getting the elements sorted ( I sometimes have the output sorted and sometime have it not sorted as above!). What I am missing or misunderstanding?
They are sorted, by the default sort order of Strings. Strings are ordered lexicographically, so "14" is considered less than "2".
If you want numerical sort order, you should have made the keys Integers instead of Strings.
One way of doing it whilst still keeping the keys as Strings would be to use the Treemap(Comparator) constructor:
static TreeMap<String, String> li = new TreeMap<>(Comparator.comparing(Integer::valueOf));
Of course, making the keys Integers also works.
If you want Integer based comparison then you need to have Integer keys in the map. Change
static TreeMap<String,String> li=new TreeMap<String,String>();
to
static TreeMap<Integer,String> li=new TreeMap<Integer,String>();
and , change put method to:
Integer key = new Random().nextInt(100);
String item = UUID.randomUUID().toString().substring(30);
li.put(key,item);
The map is ordering the keys lexicographically because they are strings (1 < 4 for the first character, and so on for the other characters).
The simplest way is to have the keys as Integers:
TreeMap<Integer,String> li=new TreeMap<>();
which will avoid the unnecessary need to convert the integer using String.valueOf.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am trying to delete all values associated with all keys in my HashMap, but still keep the keys.
Is the below correct / the most efficient way to do so?
for (Map.Entry<Kennel, List<Dog>> entry : hashMap.entrySet()) {
String key = entry.getKey().getId();
List<Dog> dogList = entry.getValue();
//Loop through the list associated with each key and delete each Dog in the list
for (int i=0; i<dogList.size(); i++){
dogService.delete(dogList.get(i));
dogService.save(dogList.get(i));
}
}
Simpler:
for(dogs : hashMap.values()) {
for(dog : dogs) {
dogService.delete(dog);
dogService.save(dog);
}
dogs.clear();
}
I don't know what you are trying to accomplish here but if you just want the unique keys then probably you should be using a HashSet instead of HashMap.
But, if you want to perform the deletion you can just do the following:
for (Kennel key : hashMap.keySet()) {
hashMap.put(key, null);
}
I have written Kennel key assuming that key of your HashMap is of type Kennel.
You could use at the end:
hashMap.put(entry.getKey(), null);
removing the whole list, but if you want put new dogs into it in the future (as I think you want), and your dog lists are modifiable, the following approach is more memory-friendly:
for (Map.Entry<Kennel, List<Dog>> entry : hashMap.entrySet()) {
String key = entry.getKey().getId();
Iterator<Dog> it = entry.getValue().iterator();
while (it.hasNext()) {
Dog dog = it.next();
dogService.delete(dog);
dogService.save(dog);
it.remove();
}
}
since you avoid allocating new lists in the future. Notice also the usage of it.remove() that allows deletion while iterating
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I want to store two integer values using an integer key, also please tell how to store and retrieve data using the key.
i already tried this :
static HashMap<Integer, User> nodes = new HashMap<Integer, User>();
public User( int b, int c) {
xco = b;
yco = c;
}
and i stored values into it as
User.nodes.put(User.key,new User((int)upx,(int)upy));
but I can't retrieve the data using the key
First of all your question isn't much describe your requirement and what have you tried so far.
But assuming your question you can try as follows.
you can create a Map<Key,Value> Integer value as a Key and Integer List<Integer> as Value
Map<Integer,List<Integer>> map=new HashMap<>();
List<Integer> list=new ArrayList<>();
list.add(1);
list.add(2);
map.put(1,list);// key is 1, values 1 and 2
you can retrieve values as follows
map.get(1) // will return list which contains values 1 and 2
Edit:
HashMap<Integer, User> nodes = new HashMap<Integer, User>();
User user=new User(1,2);// creating a user
nodes.put(1,user);
Now you can get values
nodes.get(1)// will return user
If I understand the question.
If your values ββare observably large, you can use the method: v1 * 10^n + v2
where v2 < 10^n
use SparseIntArray it is efficient way to store int key value pair
SparseIntArray sparseIntArray new SparseIntArray();
sparseIntArray.put(int_key,int_value);
while for geting value
sparseIntArray.get(int_key);
use The Map Interface
A map has the form Map <K, V> where:
K: specifies the type of keys maintained in this map.*
V: defines the type of mapped values.
you need to have an object for your 2 integer values:
class Object{
Integer int1;
Integer int2;
}
Map<Integer,Object> map;
To get value
Object result = map.get(1) // will return the first object which contain 2 integers
You can get your 2 integers using Object.int1 and Object.int2
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem β and include valid code to reproduce it β in the question itself. See SSCCE.org for guidance.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I've got 2 maps and 1 array. First map is empty and second is full of data. Array includes some String keys. So I want to put data from second map to 1st if there are some equals keys in array.
Example:
1st map: empty
2nd map(key,value): foo,1; bar,2; java,3; pojo,4; tom,5; jerry,6;
array(string): foo,java,pojo;
So I need to put (foo,1;java,3;pojo,4;) in 1st map.
public static void main(String[] args) throws IOException {
HashMap<String, Integer> map1= new HashMap<String, Integer>();
HashMap<String, Integer> map2= new HashMap<String, Integer>();
map2.put("foo", 1);
map2.put("bar", 2);
map2.put("java", 3);
map2.put("pojo", 4);
map2.put("tom", 5);
map2.put("jerry", 6);
String[] arr={"foo","java","pojo"};
for (String arrItem : arr)
{
map1.put(arrItem, map2.get(arrItem));
System.out.println(arrItem);
System.out.println(map2.get(arrItem));
}
}
Vote up / Accept the answer if this solves your query
Is this what your after?
for(int i = 0; i < myArray.length; i++)
{
if(myMap2.get(myArray[i])!=null)
myMap1.put(myArray[i], myMap2.get(myArray[i]));
}
How about:
for(String key : array) {
map2.put(key,map1.get(key);
}
Assuming all keys in the array actually exist in map1.