Search Hashmap with Integer[] as a key [duplicate] - java

This question already has answers here:
How to make HashMap work with Arrays as key?
(9 answers)
Closed 3 years ago.
Let's say that I've got a Hashmap and I would like array of two Integers to actually be the key of each value. I can't figure out how to get the correct value back. It should already be stored in the Hashmap
public class Mapky {
public static void main(String[] args) {
HashMap<Integer[], String> mapka = new HashMap<>();
mapka.put(new Integer[]{10,23}, "Hello");
System.out.println(mapka.get(new Integer[]{10,23}));
}
}
Also why does this
System.out.println(new Integer[]{10,23}.equals(new Integer[]{10,23}));
return false?

You have to provide a reference to the key.
If you create a new Integer[]{10, 23}, you will create a different one which has the same value but is not the key.
Do it like this:
public static void main(String[] args) {
Map<Integer[], String> mapka = new HashMap<>();
Integer[] key = new Integer[]{10, 23};
mapka.put(key, "Hello");
System.out.println(mapka.get(key));
}

Related

HashMap - Adding a value to a specific item [duplicate]

This question already has answers here:
How to update a value, given a key in a hashmap?
(17 answers)
Closed 11 months ago.
public void addItem(String itemName,int numItemAdd) {
HashMap <String,Integer> items = new HashMap<String,Integer>();
int totalval;
totalval =+ numItemAdd;
items.put(itemName,totalval);
}
I am new to HashMaps. I am wanting to add the integers to the specific itemName. For example, addItem("socks",100); addItem("socks",200). Whenever I do this, instead of getting 300 I only get 200. I know that put() replaces the last value used, but I do not know how to add the numbers so that I can get 300 instead of having the last value used.
You can try this, it also manages the case when socks don't exist:
private HashMap <String,Integer> items = new HashMap<String,Integer>();
public static void main(String[] args) {
Test test = new Test();
test.addItem("socks", 100);
test.addItem("socks", 200);
}
public void addItem(String itemName,int numItemAdd) {
items.put(itemName,items.get(itemName) != null ? (items.get(itemName) + numItemAdd) : numItemAdd);
System.out.println("Socks value:" + items.get(itemName));
}

How can i search in a custom object type array list ? whats is best and fastest way [closed]

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 have custom object type of array list and i want search a string is exists in objects value ,then how can i find it out that object those
have search string
You could try something like this:
package com.company;
import java.util.ArrayList;
import java.util.List;
public class Test {
private String val;
public Test(String s) {
this.val = s;
}
public static void main(String[] args) {
List<Test> values = new ArrayList<>();
values.add(new Test("one"));
values.add(new Test("two"));
values.add(new Test("three"));
System.out.println(listContains(values, "two"));
System.out.println(listContains(values, "five"));
}
public static boolean listContains(List<Test> customTypeList, String searchedString) {
return customTypeList.stream().anyMatch((v) -> v.val.contains(searchedString));
}
}
If you're searching for fastest solution and searched strings are exactly the values from objects in your list (not interested in substrings), then you may want to map strings from your objects to these object's references like this:
(...)
List<Test> values = new ArrayList<>();
values.add(new Test("one"));
values.add(new Test("two"));
values.add(new Test("three"));
Map<String, Test> indices = new HashMap<>();
for (Test v : values) {
indices.put(v.val, v);
}
System.out.println(indices.containsKey("two"));
System.out.println(indices.containsKey("five"));
// or...
System.out.println(indices.keySet().contains("two"));
System.out.println(indices.keySet().contains("five"));
(...)
IMPORTANT: You would need to update your indices whenever you change the content of your list though. Note that in this case string values inside objects must be valid keys for these objects (unique values). Example:
public static void main(String[] args) {
List<Test> values = new ArrayList<>();
Map<String, Test> indices = new HashMap<>();
addToList(values, indices, new Test("one"));
addToList(values, indices, new Test("two"));
addToList(values, indices, new Test("three"));
System.out.println(indices.keySet().contains("two"));
System.out.println(indices.keySet().contains("five"));
removeFromList(values, indices, "two");
System.out.println(indices.keySet().contains("two"));
}
private static void addToList(List<Test> values, Map<String, Test> indices, Test item) {
values.add(item);
indices.put(item.val, item);
}
private static void removeFromList(List<Test> values, Map<String, Test> indices, String key) {
Test item = indices.remove(key);
values.remove(item);
}

Nullpointerexception when I perform depth first search [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Suppose area1 has three contents 2,3,4, area2 has three contents 1,2,3 and area3 has two contents 1,2. m is the map that keys are locationid and values are list of contentid. For example, area1 has the map (1,{2,3,4}). Each area choose 1 content and find all the combination. I use dfs (recursion) to solve this problem but there is a nullpointerexception in line1. The intermediate is a list of string and i iterate through the list and their types are both string, why there is a null pointer exception? This is a specific condition in nullpointerexception and it is not duplicate.
public static List<String> dfs(String digits,Map<String, List<String>> m) {
List<String> result = new ArrayList<String>();
if(digits.length() == 0){
return result;
}
if(digits.length() == 1){
return m.get(digits.charAt(0));
}
List<String> intermediate = dfs(digits.substring(1, digits.length()),m);
for(String first : m.get(Character.toString(digits.charAt(0)))){
for(String rest : intermediate){ // line1
result.add(first + rest);
}
}
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String digits="123";
Map<String,List<String>> selected=new HashMap<>();
selected.put("1", new ArrayList<>(Arrays.asList("4","2","3")));
selected.put("2", new ArrayList<>(Arrays.asList("1","2","3")));
selected.put("3", new ArrayList<>(Arrays.asList("1","2")));
dfs(digits,selected);
}
I guess the problem is here:
return m.get(digits.charAt(0));
it should return null, since digits.charAt(0) is not a String
you need to use substring or Character.toString( here to extract the number

How to reference a variable using a string

I am attempting to reference a variable using a certain string but have no idea how to do it. I know that I can use if statements if I really had to but I am sure that there is a simple way. An example is a Integer named dog. I would try to access the Integer using another string that contained the text dog.
private int dog;
String anything = "dog";
Is there anyway this is possible? Thanks!
Try this:
// use a map for referring to a value given its name
Map<String, Integer> vars = new HashMap<String, Integer>();
// for example, let's use these values
String anything = "dog";
int dog = 10;
// bind a value to a name
vars.put(anything, dog);
// retrieve the value, given its name
vars.get(anything);
=> 10
http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
public static void main(String[] args) {
Map<String, MyObject> mapping = new HashMap<>();
}
Or new HashMap<String, MyObject>(); for pre java 7
You should use a Map of String to Integer. For example,
public static void main(String[] args) {
java.util.Map<String, Integer> dogMap = new java.util.HashMap<String, Integer>();
dogMap.put("Snoop", 10);
dogMap.put("doggy", 15);
dogMap.put("dog", 20);
System.out.println(dogMap);
}
Which outputs
{doggy=15, Snoop=10, dog=20}
Two options: create a Map<String, Object> that connects the two, or use reflection. I prefer reflection.
in order to get the field:
public class Test {
private int dog = 10;
private String anything = "dog";
public static void main(String[] args){
Test obj = new Test();
Object field = obj.getClass()
.getDeclaredField(obj.anything)
.get(obj);
System.out.println(field);
}
}
Output:
10
Create an object of the class that you will use. Then use the getDeclaredField() method on the class of that object. This will look into the private fields that are set, getField() holds only the public fields. That's it.
I've removed the try-catch from the post because it just clutters it.

how to remove duplicate array elements using hashmap in java

How to remove duplicate elements in an array using HashMap without using hashset in java...Below code describes removal of duplicates in array..
Now i need to write using hashmap for generating key and value pairs
import java.util.*;
class TestArray{
public static void main(String arg[])
{
ArrayList<String> wordDulicate = new ArrayList<String>();
wordDulicate.add("chennai");
wordDulicate.add("bangalore");
wordDulicate.add("hyderabad");
wordDulicate.add("delhi");
wordDulicate.add("bangalore");
wordDulicate.add("mumbai");
wordDulicate.add("mumbai");
wordDulicate.add("goa");
wordDulicate.add("calcutta");
wordDulicate.add("hyderabad");
ArrayList<String> nonDupList = new ArrayList<String>();
Iterator<String> dupIter = wordDulicate.iterator();
while(dupIter.hasNext())
{
String dupWord = dupIter.next();
if(nonDupList.contains(dupWord))
{
dupIter.remove();
}else
{
nonDupList.add(dupWord);
}
}
System.out.println(nonDupList);
}
}
A HashSet is implemented in terms of a HashMap anyway. If you specifically want to use a HashMap, use it the same way as HashSet does: use a dummy constant new Object() as the map value everywhere.
Well a HashMap will prevent you from entering duplicate keys, the same way as HashSet. Actually, many implementations of HashSet just use a HashMap under the hood.
So you can do:
HashMap<String, String> map = new HashMap<String, String>();
for (String s : WordDuplicate)
map.put( s, s );
Now you can access the key/values just like a HashMap.
import java.util.HashSet;
import java.util.Stack;
public class stackdupes {
public static void main(String[] args) {
Stack<Integer> st = new Stack<Integer>();
int[] arr= {1,2,3,3,4,5,5,7};
HashSet<Integer> set = new HashSet<Integer>();
for (int i=0;i<arr.length;i++) {
if(set.add(arr[i]) == true)
st.push(arr[i]);
}
System.out.println(st);
}
}

Categories