Java How do I get all map values within specific keys? - java

right now I have a Map like this:
Map<Double, MyObject> map = new HashMap<Double, MyObject>();
I want to get all values of keys that are between 2.0 and 7.0. I have thousands of different values in my Map, so looping through every key-value set will be heavy for performance. Is there any way to solve this? (Or is there some sort of special map, that is used to have number keys?) Thanks for helping ;)

Use a TreeMap instead. Through its NavigableMap interface, you can perform range operations.
NavigableMap<Double, MyObject> map = new TreeMap<>();
Collection<MyObject> keys = map.subMap(2D, 7D).values();

Related

Java Map get key from value

below is my code...
Map<Integer, String> MyType = sessionInfo.getType();
//{2=somename}
I am trying to get key from value...without running any loops....is it possible?
MyType.get("somename") // should output 2`
It's not easy to get key from value in Hashtable or HashMap, as compared to getting value from key, because Hash Map or Hashtable doesn't enforce one to one mapping between key and value inside Map in Java. infact Map allows same value to be mapped against multiple keys inside HashMap, Hashtable or any other Map implementation.
String key= null;
String value="somename";
for(Map.Entry entry: MyType.entrySet()){
if(value.equals(entry.getValue())){
key = entry.getKey();
break; //breaking because its one to one map
}
}
I would encourage running a loop for simplicity. It most likely will not slow down your program a noticeable amount.
However, if you must not run a loop, Google's Guava library has a BiDirectional Map Collection called BiMap that can be (found here). The map works both ways and is guaranteed to be synchronized at all times. I also am assuming that you have unique values in your map. If you do not, duplicate values will not have a specific key to link to.
BiMap<String, Integer> biMapInversed = biMap.inverse(); // how to get inverted map
Again, I wouldn't encourage this unless absolutely necessary. Looping through will work perfectly fine in most cases.
Taken from this SO answer
If you choose to use the Commons Collections library instead of
the standard Java Collections API, you can achieve this with ease.
The BidiMap interface in the Collections library is a
bi-directional map, allowing you to map a key to a value (like normal
maps), and also to map a value to a key, thus allowing you to perform
lookups in both directions. Obtaining a key for a value is supported
by the getKey() method.
There is a caveat though, bidi maps cannot have multiple values mapped
to keys, and hence unless your data set has 1:1 mappings between keys
and values, you cannot use bidimaps.
This is not possible. You need to consider the value may be duplicated in map.
Ex, How do you deal with {2=somename} and {5=somename}
You still need to use a for loop to check value and get key and decide to break or go on when value is matched.
If you're sure that your values are unique you can iterate over the entries of your old map .
Map<String, Character> myNewHashMap = new HashMap<>();
for(Map.Entry<Character, String> entry : myHashMap.entrySet()){
myNewHashMap.put(entry.getValue(), entry.getKey());
}
Alternatively, you can use a Bi-Directional map like Guava provides and use the inverse() method :
BiMap<Character, String> myBiMap = HashBiMap.create();
myBiMap.put('a', "test one");
myBiMap.put('b', "test two");
BiMap<String, Character> myBiMapInversed = myBiMap.inverse();

Sorting keys alphabetically in LinkedHashMap

I have a LinkedHashMap and I want to sort its keys (which are Strings) alphabetically. However, it won't work with the Collections.sort() method, because it won't take either the LinkedHashMap itself nor the LinkedHashMap's keyset.
My only option is to sort them manually while filling the LinkedHashMap, but before doing that I wanted to know if anyone knows a better way.
The better way is to use a Map which supports an order, like TreeMap.
However, if you have a broken design you can't fix you can do this.
LinkedHashMap<String, String> map = ...
TreeMap<String, String> copy = new TreeMap<>(map);
map.clear();
map.putAll(copy);
This will happen to work, but if you add a key, your map won't be sorted any more.

Storing multilple values with correspond to a key in a Map

I am beginner to java and exploring the collections I want a map of Map in which key will be of integer type and its will contains value as ulitimately I want to store in Map like..
key Value
1 abc,def,ght
2 fdr,ute,ytr
3 rds,yhj,lgt
please how can I store this in map in java.
You are looking for a Multimap.
The Guava library has an implementation for this so you don't need to implement it yourself.
You can look for details here.
If you don't like that you can simply use a Map<Integer, List<String>>:
Map<Integer, List<String>> multimap = new HashMap<Integer, List<String>>();
List<String> someList = new ArrayList<String>();
someList.add("abc");
someList.add("def");
someList.add("ght");
multimap.put(1, someList);
Use Map<Integer, String[]> or Map<Integer, List<String>>
You could have a Map<Integer, Set<String>, where the value of your map is a set of all the values the key points to.
Fortunately, there are several good implementations of such structures out there in 3rd party libraries, like Apache Commons Collections' MultiHashMap.
Have a try using
Map<Integer, List<String>>

Get ArrayList element by custom text indexing

What I'm doing is storing classes into an ArrayList and retrieve them by its index number. But are there any list classes in Java where I can retrieve a list element by, lets say, its name? Like this:
ArrayList<string> myArr = new ArrayList<string>();
myArr.add( "ID_name", "String to store" );
ands then retrieve it by:
myArr.get( "ID_name" );
Also, are there any other alternatives to ArrayList? I need a list class to be optimized for:
Random access
Only need to push items into the list
Never need to delete anything from the list
If all you want to store is key-value pairs, and don't care about iteration order, I think you might like the HashMap class:
Map<String, String> map = new HashMap<String, String>();
map.put("foo", "bar");
String bar = map.get("foo"); // bar is "bar"
You can use LinkedHashMap, so it will preserve the order, but you can extract elements by key as in regular map. Though you won't be able to extract entries by index.
An ArrayList is just that: an array. If you want to access values by something else than their indices, look for the various implementations of the Map interface (such as HashMap).
Use a Map<String, String>. In such structure, an element is added with a key. So you can get the element through the key:
Map<String, String> map = new HashMap<String, String>();
map.put("id", "string");
String s = map.get("id"); // s will be equals to "string".
As the other people have mentioned, a HashMap is probably what you want if you don't care about iteration order.
If you do, you can use a LinkedHashMap, which is really a HashMap bolted onto an LinkedList, giving you the best of both worlds: fast random access and preservation of iteration order.
Use a hashmap. You can add elements to a hashmap in much the same way as an arraylist. Also, you can create a set of keys ( 1 elements in the set per (key, value) pair)). You can then iterate over the set of keys.

Putting placeholders in a key/value List based on a Set of keys in Java

I have a Set of keys and a List of key/value pairs. The values are of the form Long,BigInteger.
// key/values pairs: Long,BigInteger
List<Object[]> values;
// id list that corresponds to the keys for the list above
Set<Long> ids;
If any member of the key Set does not exist as a key in the key/value list, I want to add it to the list with a value of 0.
What's a good way to do this in Java?
The various commenters suggesting maps make a good point. How about instead of
List<Object[]> values
you use
Map<Long, BigInteger> values
In that case:
for(Long id : ids) {
if(!values.containsKey(id)) {
values.put(id, BigInteger.ZERO);
}
}
In fact, even if the code as must be kept as written I'd consider using a map for manipulation by pre-processing the list into a map, then dumping it back into the list of object arrays.
What's a good way to do this in Java?
Replace the Set<Long> and List<Object[]> by a Map<Long, BigInteger>. If the ordering is not important, then use HashMap. If you'd like to sort automagically on keys, then use TreeMap. If you'd like to maintain insertion order, then use LinkedHashMap.
E.g.
Map<Long, BigInteger> unorderedMap = new HashMap<Long, BigInteger>();
Map<Long, BigInteger> orderedByKeys = new TreeMap<Long, BigInteger>();
Map<Long, BigInteger> orderedByInsertion = new LinkedHashMap<Long, BigInteger>();
This way you can just use any of the Map methods to handle key/value pairs. E.g.
Long key = 1L;
BigInteger value = map.get(key);
if (value == null) {
value = new BigInteger(0);
map.put(key, value);
}
You can even get all keys by Map#keySet():
Set<Long> keys = map.keySet();
To learn more about maps, consult Sun's own tutorial about the subject.
I think you want to use something like one of the Google Collections Multimap implementations. Don't re-invent the wheel. The Apache Commons has something similar I suspect, but I prefer the Google library.
Querying for a key that has no values returns an empty collection.
EDIT: options for sorting order, uniqueness, etc are all available, just pick the right implementation according to your requirements.

Categories