Is there something like a KeyValuePair in Java?
I have a Very long list of elements of the following class:
public class Foo {
int id;
Set<String> items;
}
which is stored here:
LinkedList<Foo> myList;
each time I search for a item, I iterate over the list and search for the Item, but this takes to much time.
I want to do something like this:
myList.get(123) => items of the Foo with id = 123
You can use Map in Java for that purpose. It will allow key, value pairs.
Map<Integer,Set<String>> map = new HashMap<Integer,Set<String>>();
Adding item to map
Set<String> set = new HashSet<String>();
set.add("ABC");
set.add("DEF");
map.put(123,set);
Getting item from map
map .get(123) will give Set<String> associated with id 123
Try some impelementation of java.util.Map.
More info: here
I think the MultiMap<Integer,String> is suitable in your case.
Guava MultiMap
Apache commons MultiMap
you would need a so called MultiMap, java dont has that by default, but you always can use a Map for that purpose.
Try using a HashMap<Integer, Set<String>>
import java.util.*;
class temp{
public static void main(String[] args){
Map<Integer,String> map = new HashMap<Integer,String>();
map.put(1,"anand");
map.put(2,"bindu");
map.put(3,"cirish");
System.out.println(1+" = "+map.get(1));
System.out.println(2+" = "+map.get(2));
System.out.println(3+" = "+map.get(3));
Map<String,Integer> map1 = new HashMap<String,Integer>();
map1.put("anand",1);
map1.put("bindu",2);
map1.put("cirish",3);
System.out.println("anand = "+map1.get("anand"));
System.out.println("bindu = "+map1.get("bindu"));
if(map1.get("cirish") != null){
System.out.println("cirish = "+map1.get("cirish"));
}
if(map1.get("dinesh") != null){
System.out.println("cirish = "+map1.get("dinesh"));
}
}
}
Related
I am wondering how to build a nested Map and then retrieve the nested key:value pairs. This is how I created the map to be nested.
//Create List of Nested HashMaps
List<Map> nestedMap = new ArrayList<>();
nestedMap.add(building3Map);
nestedMap.add(building31Map);
nestedMap.add(buildingHFTFMap);
System.out.println("The nested map is: " + nestedMap);
This is the system output for the following code:
The nested map is: [{buildingname=[Building 3], buildingid=[3]}, {buildingname=[Building 31], buildingid=[1]}, {buildingname=[HFTF], buildingid=[4]}]
This is correct as I want a list of maps. But the next step is what is confusing to me. When I try to build the outer layer Map as below:
HashMap<String, List<Map>> queryMap = new HashMap<>();
queryMap.put("buildings", nestedMap);
System.out.println(queryMap.get("buildings.buildingid"));
I get a system output of null when attempting the .get("buildings.buildingid") method. Ideally, I need the output to look like this:
[[3, 1, 4]]
Where it returns all values with a key of "buildings.buildingid" in an array. I am new to coding so please let me know if I'm making any fundamental errors and how I can create a nested Map where I can access the inner layer or if there is another method I should be using.
I think you are making it way too complicated than it should be. you can store your data in a simple map where the ids are the keys for example and the names are the values. So you only need to read the keys or the values from the map to get your result.
Map<Integer, String> myMap = new HashMap<>();
myMap.put(3, "Building 3");
myMap.put(31, "Building 31");
myMap.put(4, "HFTF");
System.out.println(myMap.keySet());
System.out.println(myMap.values());
However, Java is an object-oriented language. If it makes sense for your use case you might want to create a custom class "Building" instead of frantically trying to store your data in nested data structures. See below for an example of how it might look using a custom class:
import java.util.ArrayList;
import java.util.List;
public class Example {
public static void main(String args[]) {
List<Building> buildings = new ArrayList<>();
buildings.add(new Building(3, "Building 3"));
buildings.add(new Building(31, "Building 31"));
buildings.add(new Building(4, "HFTF"));
List<Integer> buildingIds = new ArrayList<>();
buildings.forEach(building -> buildingIds.add(building.getBuildingId()));
List<String> buildingNames = new ArrayList<>();
buildings.forEach(building -> buildingNames.add(building.getBuildingName()));
System.out.println(buildingIds);
System.out.println(buildingNames);
}
public static class Building {
int buildingId;
String buildingName;
public Building(final int buildingId, final String buildingName) {
this.buildingId = buildingId;
this.buildingName = buildingName;
}
public int getBuildingId() {
return buildingId;
}
public void setBuildingId(final int buildingId) {
this.buildingId = buildingId;
}
public String getBuildingName() {
return buildingName;
}
public void setBuildingName(final String buildingName) {
this.buildingName = buildingName;
}
}
}
queryMap.get("buildings.buildingid") returns null, because queryMap only contains a value under the key
buildings. A HashMap can only access the value using the same key it was stored under. The key and the value is not processed in any further way.
A simple alternative could be
queryMap.get("buildings").stream() // Create a Stream<Map>
.map(building -> building.get("buildingid")) // Create Stream<String> by extracting the buildingid values.
.collect(Collectors.toList()); // Collect Stream into a List<String> which contains the buildingid's
If you don't like this solution you could take a deeper look into property expressions, and write your own map implementation that can resolve these expressions. But it will be a lot of work to get it working correctly...
I am working with on line store project. At the moment I am trying to add possibility to add products to the shopping cart, no matter if user is logged in or not. I am using session bean method to do it.
#Inject ShoppingCartSessionBean shoppingCartSessionBean;
#POST
public boolean addToCart(#PathParam("productid") int newProductId, #PathParam("qu") int newProductQuantity) {
shoppingCartSessionBean.setCartItems(newProductId);
shoppingCartSessionBean.setProductQuantity(newProductQuantity);
return true;
}
I would like to store id's in hash map. However, at the moment I can set only one id for my setter method.
#Stateful
#SessionScoped
public class ShoppingCartSessionBean implements Serializable{
HashMap<Integer, Integer> newmap = new HashMap<Integer, Integer>();
public int addToHashMap() {
return array of productId's.
}
private static final long serialVersionUID = -5024959800049014671L;
private int productId;
private int productQuantity;
//getters and setters
Map<Integer, ShoppingCartSessionBean> hm = new HashMap<Integer, ShoppingCartSessionBean>();
Later I am using entity manager to check which id's / id were set and send back all information about that id to the user. I am not storing all values in session bean because of space issues.
Query q = em.createQuery("SELECT c FROM Items c WHERE c.productId = :itemid");
q.setParameter("itemid", shoppingCartSessionBean.addToHashMap());
So I have a few questions:
Is it good choice to store such information in hash map? Or should I use cookies instead?
How my addToHashmap method should look like to store multiple id's in hash map? (I tried a simply int[] array = {123, 456} to print out using my entity manager, however I got JSON error...).
What is the best way to remove / unset such information from hash map?
I hope my information is clear, if you are missing something - let me now.
Point 2 and 3. You need to check if there is a hash collision, in positive case you need to treat it. Look the code below.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class HashMapTest {
private static HashMap<String, List<String>> map = new HashMap<String, List<String>>();
public static void insert(String key, String value){
List<String> list = map.get(key);
if (list == null){
list = new ArrayList<String>();
map.put(key, list);
}
list.add(value);
}
public static void main(String[] args){
insert("10", "V1");
insert("10", "V2");
insert("20", "V3");
insert("20", "V4");
insert("30", "V5");
List<String> values10 = map.get("10");
System.out.println(values10);
List<String> values20 = map.get("20");
System.out.println(values20);
List<String> values30 = map.get("30");
System.out.println(values30);
}
}
I have a List of Strings and I'm trying to have a method that tells me which String has more occurrences in the List.
Here is what I've done so far:
package codekata;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class OcurrenciasEnLista {
public static void main(String[] args) {
List<String> lista = new ArrayList<String>();
lista.add("test");
lista.add("foo");
lista.add("foo");
lista.add("foo");
lista.add("bar");
lista.add("crack");
moreOftenWord(lista);
}
private static void moreOftenWord(List<String> lista) {
Map<String, Integer> mapa = new HashMap<String, Integer>();
for (String palabra: lista)
addOrIncrementCount(mapa, palabra);
}
private static void addOrIncrementCount(Map<String, Integer> counters,
String toAdd) {
Integer currValue = counters.get(toAdd);
if (currValue == null)
counters.put(toAdd, 1);
else
{
counters.put(toAdd, currValue + 1);
}
}
}
What I don't know how to do is to return -the word- already in the moreOftenWord method.
Can anybody give me a clue on this?
The most common element in a list is called the "mode" of the list.
http://www.dreamincode.net/forums/topic/39745-get-mode-of-a-list/ is the first result for "mode of a list java" that looks relevant in case you want a code sample.
To get at the most common element after you've built your map of counters, you probably want to do something like
Map.Entry<String, Integer> mode = null;
for (Map.Entry<String, Integer> e : counters.entrySet()) {
if (mode == null || mode.value() < e.value()) {
mode = e;
}
}
// Most common string in mode.getKey()
This assumes that you redefine
Map counters
generically as
Map<String, Integer> counters
The Multiset data structure maintains a count of each element added to it. So you can remove all boilerplate code if you use this. Then all you need to do is iterate through the Multiset and find the element that has the max count.
Guava library has many such useful data structures and more.
In statistics, this is called the "mode" (as Mike's answer already explained). jOOλ is a library that supports mode() on streams. The following program:
System.out.println(
Seq.of("test", "foo", "foo", "foo", "bar", "crack")
.mode()
);
Yields:
Optional[foo]
(disclaimer: I work for the company behind jOOλ)
This question already has answers here:
Java Hashmap: How to get key from value?
(39 answers)
Closed 5 years ago.
I want to get the key of a HashMap using the value.
hashmap = new HashMap<String, Object>();
haspmap.put("one", 100);
haspmap.put("two", 200);
Which means i want a function that will take the value 100 and will return the string one.
It seems that there are a lot of questions here asking the same thing but they don't work for me.
Maybe because i am new with java.
How to do it?
The put method in HashMap is defined like this:
Object put(Object key, Object value)
key is the first parameter, so in your put, "one" is the key. You can't easily look up by value in a HashMap, if you really want to do that, it would be a linear search done by calling entrySet(), like this:
for (Map.Entry<Object, Object> e : hashmap.entrySet()) {
Object key = e.getKey();
Object value = e.getValue();
}
However, that's O(n) and kind of defeats the purpose of using a HashMap unless you only need to do it rarely. If you really want to be able to look up by key or value frequently, core Java doesn't have anything for you, but something like BiMap from the Google Collections is what you want.
We can get KEY from VALUE. Below is a sample code_
public class Main {
public static void main(String[] args) {
Map map = new HashMap();
map.put("key_1","one");
map.put("key_2","two");
map.put("key_3","three");
map.put("key_4","four");
System.out.println(getKeyFromValue(map,"four"));
}
public static Object getKeyFromValue(Map hm, Object value) {
for (Object o : hm.keySet()) {
if (hm.get(o).equals(value)) {
return o;
}
}
return null;
}
}
I hope this will help everyone.
If you need only that, simply use put(100, "one"). Note that the key is the first argument, and the value is the 2nd.
If you need to be able to get by both the key and the value, use BiMap (from guava)
You have it reversed. The 100 should be the first parameter (it's the key) and the "one" should be the second parameter (it's the value).
Read the javadoc for HashMap and that might help you: HashMap
To get the value, use hashmap.get(100).
You mixed the keys and the values.
Hashmap <Integer,String> hashmap = new HashMap<Integer, String>();
hashmap.put(100, "one");
hashmap.put(200, "two");
Afterwards a
hashmap.get(100);
will give you "one"
if you what to obtain "ONE" by giving in 100 then
initialize hash map by
hashmap = new HashMap<Object,String>();
haspmap.put(100,"one");
and retrieve value by
hashMap.get(100)
hope that helps.
public class Class1 {
private String extref="MY";
public String getExtref() {
return extref;
}
public String setExtref(String extref) {
return this.extref = extref;
}
public static void main(String[] args) {
Class1 obj=new Class1();
String value=obj.setExtref("AFF");
int returnedValue=getMethod(value);
System.out.println(returnedValue);
}
/**
* #param value
* #return
*/
private static int getMethod(String value) {
HashMap<Integer, String> hashmap1 = new HashMap<Integer, String>();
hashmap1.put(1,"MY");
hashmap1.put(2,"AFF");
if (hashmap1.containsValue(value))
{
for (Map.Entry<Integer,String> e : hashmap1.entrySet()) {
Integer key = e.getKey();
Object value2 = e.getValue();
if ((value2.toString()).equalsIgnoreCase(value))
{
return key;
}
}
}
return 0;
}
}
If you are not bound to use Hashmap, I would advise to use pair< T,T >.
The individual elements can be accessed by first and second calls.
Have a look at this http://www.cplusplus.com/reference/utility/pair/
I used it here : http://codeforces.com/contest/507/submission/9531943
I have a hashmap like this
public HashMap <String,People> valueHashMap = new Hashmap();
Here the key to my HashMap is time in seconds as string, ie I am adding value to hashmap like this
long timeSinceEpoch = System.currentTimeMillis()/1000;
valueHashMap.put(
Integer.toString((int)timeSinceEpoch)
, people_obj
);
Now I want to get all keys in the hashmap into an array list of integer.
ArrayList<Integer> intKeys = valueHashMap.keys()...
Is there any way to do that?
There is no direct way of converting a list of Strings to a list of Integers:
Either you need to redefine your valueHashMap like this:
public HashMap<Integer, People> valueHashMap = new HashMap<Integer, People>();
....
ArrayList<Integer> intKeys = new ArrayList<Integer>(valueHashMap.keySet());
Or you need to loop:
ArrayList<Integer> intKeys = new ArraList<Integer>();
for (String stringKey : valueHashMap.keySet())
intKeys.add(Integer.parseInt(stringKey);
I would advice you however to use the Long as key instead:
public HashMap<Long, People> valueHashMap = new HashMap<Long, People>();
then there would be no casting to int (and you can use (1) above with Long instead).
You can't cast a List of one type to a List of another type, so you have to iterate through the keys and parse each one.
for(String k : valueHashMap.keySet()) {
intKeys.add(Integer.valueOf(k));
}
You really have type problems. Why do you change the longs into Strings to store them in a map. Why not simply use Long, which needs less memory and is more descriptive. Then why use Integer.toString to transform a long into a String? By casting your long to an int, you risk loosing information by. Here's how the code should probably look like:
private Map<Long, People> valueHashMap = new Hashmap<Long, People>();
long timeSinceEpoch = System.currentTimeMillis()/1000;
valueHashMap.put(timeSinceEpoch, people_obj);
List<Long> longKeys = new ArrayList<Long>(valueHashMap.keySet());
You can use org.apache.commons.collections.Transformer class for that as follows.
List<Integer> intKeys = (List<Integer>)CollectionUtils.collect(valueHashMap.keySet(), new Transformer() {
#Override
public Object transform(Object key) {
return Integer.valueOf(key);
}
}, new ArrayList<Integer>());