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
Related
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?
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 5 years ago.
Improve this question
I have an ArrayList like this:
[{1=R111, 2=Red, 3=50000}, {1=R123, 2=Blue , 3=50000}]
and i want to remove the array by value (R111 or R123).
how to remove the array using array.remove method for array like that?
I've try this link
but it's doesn't work for my problem.
Assuming your ArrayList is this:
List<String[]> arrayList = new ArrayList<>();
arrayList.add(new String[]{"R111","Red","50000"});
arrayList.add(new String[]{"R123","Blue","50000"});
you can do something like:
for (Iterator<String[]> iterator = arrayList.iterator();iterator.hasNext();) {
String[] stringArray = iterator.next();
if("R111".equals(stringArray[0])) {
iterator.remove();
}
}
You can safely remove an element using iterator.remove() while iterating the ArrayList. Also see The collection Interface.
An alternative shorter approach using Streams would be:
Optional<String[]> array = arrayList.stream().filter(a -> "R111".equals(a[0])).findFirst();
array.ifPresent(strings -> arrayList.remove(strings));
Thanks pieter, I used Iterator like this:
for (Iterator<HashMap<String, String>> iterator = RegulerMenu.iterator(); iterator.hasNext();) {
HashMap<String, String> stringArray = iterator.next();
if("R111".equals(stringArray.get("1"))) {
iterator.remove();
}
}
It's work now, Thankyou verymuch.
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 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 7 years ago.
Improve this question
I am trying to search for a specific value in a HashMap, using an iterator, currently I have this method. I am very new to Java so your help would be greatly appreciated. helper.readAMap is hashmap which stores responses, which are generated when a user types in a certain word.
public String generateResponse(String words)
{
HashMap<String, String> map = new HashMap();
map = helper.readAMap("replies.txt");
Iterator<String> it = map.keySet();
while(it.hasNext()) {
String word = it.next();
String response = map.get(word);
if(response != null) {
return response;
}
}
return pickDefaultResponse();
}
Here:
if(key.equals(words)) {
You compare a String to a HashSet of Strings. That is like comparing an apple to a pear; it will always be false.
So you either want a single String as argument to your method, or you want to generate responses to all of the words.
I expect you want to do this:
if(words.contains(key)) { // Your input contains the key
return map.get(key); // Retrieve the response to the key from the map
}
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 8 years ago.
Improve this question
I've tried to search the WWW but failed to find an answer. Couldn't find one here either.
Here's my question:
How do I get a specific name(element?) from a Customer in an ArrayList?
I'm imagining it looks something like this:
ArrayList<Customer> list = new ArrayList();
String name = list.get(2) // which would return the Customer at 2's place.
But what if I want to search for a customer by name, lets say a customer named Alex? How do I do that?
Bonus question: How do I then delete that customer?
As others have said this isn't all that efficient and a HashMap will give you fast lookup. But if you must iterate over the list you would do it like this:
String targetName = "Jane";
Customer result = null;
for (Customer c : list) {
if (targetName.equals(c.getName())) {
result = c;
break;
}
}
If you need to remove an item from a list while iterating over it you need to use an iterator.
String targetName = "Jane";
List<Customer> list = new ArrayList<Customer>();
Iterator<Customer> iter = list.iterator();
while (iter.hasNext()) {
Customer c = iter.next();
if (targetName.equals(c.getName())) {
iter.remove();
break;
}
}
Your are going to have to iterate through your array using something like this in a function call.
void int HasName(string name){
for(int i=0; i < list.size(); i++) {
String s = list.get(i).getName();
//search the string
if(name.equals(s)) {
return i
}
}
return -1
}
If you really need to search by name consider looking into HashMap.
With an ArrayList, you have to loop... If you can, use a Map (HashMap, TreeMap) to quickly find an element.
This works if you always seek by name, for example. (use name as key of the map)
There isn't a way to explicitly do what you want, unless you want to iterate through the whole collection, comparing the desired name to the current one. If you want this type of functionality, you could try a Map such as HashMap.
Implement equals and hashcode for Customer object. Use customer name attribute for this.
Use ArrayList.indexof to find the index of the element. use the remove method in Arraylist to remove the object by index.