Retrieve all entries from Map<Integer, String> with keys in certain range - java

I need to have a HashMap< Integer, String> which can serve fast operations for retrieving a list of all entries whose keys are in a certain integer range besides, getting values from map based on keys.
What Map implementation is suitable for these needs ?

You are probably looking for a NavigableMap. However, you can't use HashMap to create one, because the map would have to be a SortedMap. Consider using TreeMap instead.

Use a TreeMap, which implements NavigableMap supplying a subMap method returning a view of the map with only keys in your range. To get the values, of course you call values() on the result.
If you have an existing Map whose keys implement Comparable, you can construct a TreeMap from it by calling new TreeMap(existingMap), but it will likely be more efficient to create it as a TreeMap from the start.

TreeMap will provide a sorted list of keys. You would then need to trim the list to get your range of values.

Related

Sorting collection in java

I have a HashMap which has keys as Date in Strings and value as an ArrayList of custom objects. I want to sort this hashmap on the basis of key. How can I do that?
HashMap<String,List<ClassName>> hashmap = new HashMap<String,List<ClassName>>();
When Hashmap is like this:
{"2015/07/15 : List("Object1","object2","object3")
"2015/07/14 :List("Object4" , "Object5")}
Please suggest.
You can use TreeMap instead of a HashMap . The TreeMap implements the Sorted Map interface.
As well as using a sorted map (as others have suggested) you can easily sort the keys when you use them rather than when you insert them.
For example, in Java 8:
treeMap.keySet().stream().sorted().forEach(System.out:println);
A nice thing about this is that it's easy to sort using different comparators without changing the collection.
For example, if you wanted to to sort by the number of items in the list value:
treeMap.keySet().stream().sorted(Comparator.comparingInt(k -> treeMap.get().size()))
This method is good for situations in which you insert and change values in the map often and then occasionally need the keys sorted for a particular operation. You get the performance of a HashMap but the flexibility to sort however you want on use.
You can use TreeMap, if you need the sorted map.
If you don't want to use TreeMap, then get the key and sort it as below.
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
map.put("2015/07/15", list);
map.put("2015/07/17", list1);
map.put("2015/07/16", list1);
ArrayList<String> keyset = new ArrayList<String>(map.keySet());
Collections.sort(keyset);
First thing is you can use TreeMap when you need a sorted map. However you are storing date value as Strings. Then it become harder to compare each. So i recommend to use java.util.Date instead of String. You can use a date formatter when you adding to the map. Use following code.
TreeMap<Date, List> treeMap = new TreeMap<>();
You can specify the Comparator in the constructor of the TreeMap. So it's easy to sort up things according to your custom order.

Storing Key, Value Pair using java

I would like to know the best data structure used in java suitable for the following senario.
There is a key and a value.
And the key is not duplicated,
Each Value should store collection of objects where the values in each object will change frequently.
Thanks.
HashMap should serve your need.
HashMap allows you to store key value pairs as a collection. HashMap does not allow duplicate keys. You can use different collection to be stored as a value in your HashMap. For example to create a map with keys as a String and value as a list, the define it like this:
Map<String, List<String>> = new HashMap<String, List<String>>();
Also there are implementations for such collection called MultiMap i.e map where a key is associated with collection of values. Two popular implemantations of MultiMap are:
Apacha MultiMap
Guava MultiMap
A type of map. You aren't saying much besides "I need a key-value thingy". If you need to iterate the map by insertion order, there is a LinkedHashMap. If you need to iterate the map by ascending or descending key values, there are sorted maps. If the map will be shared by multiple threads a concurrent map will be useful. If there will be billions of items in the list and you don't mind hemorraghing data (say this is a caching algorithm), a WeakHashMap is for you.
If by "key is not duplicated" you mean it is a violation if a key is inserted if it already exists, you have a few options.

Sorting an hashmap with Integer as Key and ArrayList

I have situation where there is a HashMap as
Map<Integer,ArrayList> key = new HashMap<Integer,ArrayList>();
The array list has [rankOfCard,suitOfCard]
I want to sort this Map in such a way that If the value is
(1,[3,1])
(2,[2,4])
(3,[1,3])
(4,[1,2])
(5,[2,3])
Output should be :
(4,[1,2])
(3,[1,3])
(5,[2,3])
(2,[2,4])
(1,[3,1])
How can I achieve this ?
Iterate through entry set and Collection.sort(entry.value())
A Map is not sorted, so it's not the right data structure for your task.
A SortedMap sorts on keys, so it's no good as well, since you want your map sorted by value.
Your question does not clarify what the key of the Map is, but maybe you could use a custom class in a regular List, and have the class implement the Comparable interface, or implement an external Comparator, to sort the List.

Java - making objects with key/value pairs?

I want to make the following types of objects. This is my higher-level desire that I'd like to figure out in Java:
ListObject(key, String): every key corresponds to a String value; key is a string itself
ListObject(key, String[]): every key corresponds to an array of Strings; key is a string itself
ListObject(key, String, String[]): same deal but with two value fields per key.
How would I make (and use!) objects of this type?
Thanks.
You seem to need some Maps rather than Lists. Check the Javadoc for Map implementations; the most common is HashMap, but there are sorted, concurrent, deterministically iterable implementations etc. available too.
ListObject: every key corresponds to a String value; key is a string itself
Map<String, String>
ListObject: every key corresponds to an array of Strings; key is a string itself
Map<String, String[]>
(or preferably Map<String, List<String>>)
ListObject: same deal but with two value fields per key.
Map<String, UserDefinedClassWithTwoFields>
Map<KeyType,ValueType> which is implemented by HashMap<KeyType, ValueType> and TreeMap<KeyType, ValueType>, among others -- HashMap is unordered and TreeMap is ordered.
Other useful Maps are LinkedHashMap which is like HashMap but iterates in insertion order, and com.google.common.collect.Maps in Guava which has a bunch of utility methods, and com.google.common.collect.ImmutableMap which is an immutable map implementation.
For your key corresponding to an array of strings, you might want to look at a Multimap which is a map with multiple values for a given key.
You could use Map for this purpose.
The general syntax for Map is:
Map<String, SomeObject> = new HashMap<String, SomeObject>();
Now there are four kinds of Maps in java:
HASH MAP - Use this map when you don't care about the order in which elements are displayed when you iterate over the map.
HASH TABLE - Synchronized version of hash map.
LINKED HASH MAP - Use this when you care about the insertion order.
TREE MAP - Use this when you want custom sort order.
Map are used to create associative arrays in Java.
Map for your first example. Each String key is associated to a String value.
Map for your second example. Values are arrays of String.
For your last example, you have to create you own class with two fields: one a String and one a String[]. Then, create a map that associates String to an object of your type.
Java's Map type would most likely do the trick. A Map<KeyType, ValueType> stores key-value pairs, so you would have a Map<String, String>, a Map<String, List<String>>, and a Map<String, SomePairType>.
Map is just an interface: you have to pick an implementation. HashMap and TreeMap are your best bets. Both are good, but TreeMap will only work with comparable key types.
For keys, since String is comparable with other Strings, you could use either map implementation.

Built-In way to store Pre-Sorted Key-Value Pairs in Java?

I'm looking for a way to maintain the sorting on my key-value pairs. They are sorted by variables outside of the actual key-value pairs (for better UI). I am currently using a Hashtable, but that does not maintain the sorting =(
Hashtable<Integer, String> subscriptions = getUsersSubscriptions(user);
Is there some simple way that Java lets one store pairs? The best idea I can think of is using 2 associated ArrayLists (one of type Integer, another of type String). Can someone think of something better?
If your key-value pairs are already sorted, LinkedHashMap will maintain order of insertion.
In other words, the keys returned by map.keySet() will be in the exact order you put them into the map.
SortedMap<Integer, String> myMap = new TreeMap<Integer,String>();
If you have a custom sorting, pass a Comparator instance to the constructor of the TreeMap. But be careful doing so, as using a Comparator that does not go well with natural Integer order would make things impossible to understand and debug.
LinkedHashMap can be used here.
Is there some simple way that Java lets one store pairs?
Create a custom class that stores the two properties.
They are sorted by variables outside of the actual key-value pairs
Add a third property for the sort data.
Then your class can implement Comparable to sort the data as required based on this property.
Or you can use a custom Comparator to sort on the sort data field.
Now the class instances can be stored in an ArrayList.

Categories

Resources