I have a parameter map incoming from a post in a web form. The problem I have is that I want to have the key values sorted.
I have two keys incoming j_idt40:j_idt41:0:score and j_idt40:j_idt41:0:scoreID These I would either want to find without resorting to loop through the map for every row I iterate again. Is there a better way to do this?
j_idt40:j_idt69 = Uppdatera
j_idt40:j_idt41:3:score = 200
j_idt40:j_idt41:0:scoreID = 1
j_idt40:j_idt41:4:scoreID =
j_idt40:j_idt41:3:scoreID = 4
j_idt40:j_idt41:2:scoreID = 3
j_idt40:j_idt41:0:score = 203
j_idt40:j_idt41:2:score = 200
j_idt40:j_idt41:1:score = 200
j_idt40 = j_idt40
j_idt40:j_idt41:4:score = 800
j_idt40:j_idt41:1:scoreID = 2
Natural sorting you need to write your own comparator. The existing comparators in jdk will fail on the following scenario.
TreeMap<String,String> treeMap = new TreeMap<String, String>();
treeMap.put("key1", "value");
treeMap.put("key2", "value");
treeMap.put("key20", "value");
treeMap.put("key10", "value");
treeMap.put("key11", "value");
treeMap.put("key21", "value");
The sorting will happen like this.
key1,key10,key11,key2,key20,key21
Natural sorting is implemented in Java 8 see here
or
Use apache commons ComparatorUtils.NATURAL_COMPARATOR
will TreeMap help you in this regard ?
TreeMap Keeps everything sorted. This is built-in class in Java collection API.
You can use this constructor to convert your map to sorted map.
TreeMap(Map m) // this is from 'java.util.TreeMap'
You can pull all the Map.Entries out into a list, sort that, then loop through it once. You've have to make a Comparitor for Map.Entries.
You can sort the keys like this:
Collection<?> keys = params.keySet();
String[] array = keys.toArray(new String[keys.size()]);
Arrays.sort(array);
Or if you want the entries of the map to be ordered, you can achieve this by inserting them into a TreeMap. When you iterate the TreeMap's key set they come out in order.
Which approach is more "efficient" depends on what measure of efficiency you are talking about (CPU, memory, developer time).
It also depends on how often various things are performed by your application. For example:
lookup, insert and delete operations are on average O(1) for a HashMap and O(logN) for a TreeMap
iterating a TreeMap's key set is O(N)
extracting and sorting a Hashmap's keys is O(NlogN)
Related
Is there any way where I can assert 2 lists of Maps ignoring the order? thanks
Example:
List<Map<String, Object>> dataList1 = new ArrayList<>();
List<String> headers1 = new ArrayList<>();
headers1.add("Header1");
headers1.add("Header2");
headers1.add("Header3");
Map<String, Object> dataMap1 = new LinkedHashMap<>();
dataMap1.put(headers1.get(0), "testData1");
dataMap1.put(headers1.get(1), "testData2");
dataMap1.put(headers1.get(2), "testData3");
Map<String, Object> dataMap2 = new LinkedHashMap<>();
dataMap2.put(headers1.get(0), "testData4");
dataMap2.put(headers1.get(1), "testData5");
dataMap2.put(headers1.get(2), "testData6");
dataList1.add(dataMap1);
dataList1.add(dataMap2);
List<Map<String, Object>> dataList2 = new ArrayList<>();
List<String> headers3 = new ArrayList<>();
headers3.add("Header1");
headers3.add("Header2");
headers3.add("Header3");
Map<String, Object> dataMap3 = new LinkedHashMap<>();
dataMap3.put(headers3.get(0), "testData1");
dataMap3.put(headers3.get(1), "testData2");
dataMap3.put(headers3.get(2), "testData3");
Map<String, Object> dataMap4 = new LinkedHashMap<>();
dataMap4.put(headers3.get(0), "testData4");
dataMap4.put(headers3.get(1), "testData5");
dataMap4.put(headers3.get(2), "testData6");
dataList2.add(dataMap4);
dataList2.add(dataMap3);
System.out.println(dataList1);
System.out.println(dataList2);
and the results would be:
[{Header1=testData1, Header2=testData2, Header3=testData3}, {Header1=testData4, Header2=testData5, Header3=testData6}]
[{Header1=testData4, Header2=testData5, Header3=testData6}, {Header1=testData1, Header2=testData2, Header3=testData3}]
I want to get a TRUE result since they are actually the same but with different order. thank you in advance!
EDIT:
Just to add. I am trying to check if the 2 lists of maps are equal from 2 different sources (Excel file vs Database data). so there's a chance that the lists of data have duplicates.
That is not what a list is for. If you don't care about the order, you should use a Set instead.
However if the order is important but you just want to make sure they contain the same Maps then you could just convert them to Sets for the assertion:
new HashSet<Map<String, Object>>(dataList1).equals(new HashSet<Map<String, Object>>(dataList2))
In the case you're describing the value lists would rather have "bag" semantics, i.e. sets which contain duplicates.
To compare those you need to write your own comparison logic (or find a library that provides it, e.g. Apache Commons Collections' CollectionUtils#isEqualCollection() or Hamcrest's Matchers#containsInAnyOrder()) since the default methods won't help. The assert would then be something like assertTrue(mapsAreEqual(actual, expected)) or assertEqual(new MapEqualWrapper(actual), new MapEqualWrapper(expected)) where MapEqualWrapper would implement the logic in its equals().
For the check you could sort the lists (or copies of them) and do a traditional comparison or use a frequency map (after other checks of course):
first check the sizes - if they are different the lists aren't equal
build a frequency map for the first list, i.e. increment the value by 1 for each occurence
check the elements in the second list by decreasing the occurences and removing any frequencies that hit 0
if you hit an element that has no entry in the frequency map you can stop already since the bags aren't equal
Sorting and comparing would be easier to implement with just a couple of lines but time complexity would be O(n*log(n)) due to the sorting.
On the other hand, time complexity for using the frequency map would basically be O(n) (iterations are O(n) and map put/get/remove should be O(1) in theory). This, however, shouldn't matter unless you need to quickly compare large lists and thus I'd go with the sort and compare method first.
I have a Map of Long and String - Map which stores my timestamp as the key and value as my data.
Map<Long, String> eventTimestampHolder = new HashMap<Long, String>();
Now I want to get 100 most recent data from the above map by looking at timestamp which is part of key and then keep on adding those data in a List of String. In general populate the 100 most recent data in a List.
What is the best way to do this? Can I use TreeMap here and it will sort my keys basis on the timestamp properly?
In general my timestamp is going to look like this - 1417686422238 and it will be in milliseconds
In case you mean by "recent" recently added, then you can try LinkedHashMap which will maintain the order of insertion. Then you can iterate over the first 100 items.
You can iterate over the map like this:
for(Long key : eventTimestampHolder.keySet()) {
String value = eventTimestampHolder.get(key);
}
For any key that can be sorted, you should use a SortedMap (unless there are other requirements making it unsuitable). A TreeMap is a sorted map. Since you need the most recent k entries, you need the largest keys first. This can be done by going through the k first keys in the map's descendingKeySet as follows, a one-liner in Java-8:
eventTimestampHolder.descendingKeySet().stream().limit(k); // in your case, k = 100
If you want not just the keys, but the values as well, then you could find the k'th key, and then use
// the 2nd arg is a boolean indicating whether the k'th entry will be included or not
eventTimestampHolder.tailMap(kthTimestamp, true);
One thing to remember when using tailMap is that it will be backed by the original eventTimestampHolder map, and any changes to that will be reflected in the returned tail map.
Below is a piece of code which I use for inserting the values in a hashmap.
String[] folders={"Movies/HD/By Genre/Action","Movies/HD/By Genre/Comedy"};
HashMap<String, String> sdsResults = new HashMap<String, String>();
for(int i=0; i<folders.length; i++){
sdsResults.put(folders[i], null);
}
Iterator<String> itr = sdsResults.keySet().iterator();
while(itr.hasNext()){
System.out.println("keys in map are = "+itr.next());
}
The output is -
keys in map are = Movies/HD/By Genre/Comedy
keys in map are = Movies/HD/By Genre/Action
Now I wanted to keys to come in the same order as how I had put in. i.e. first the Action one should come and then the Comedy. But reverse order is coming.
Can someone explain why is it so? And I want the order to be the same as the folder contents. How can I achieve this?
The order of keys in a hash is not defined. You want a map. Here's a comparison of the internals.
Basically, when you put something in a hash, you scramble the key. This is a one-way function. The whole point is that you can't un-do it -- it's a way of putting 100 things in 10 boxes.
LinkedHashMap should solve the problem of ordering.
Similar question and the answer here Order of values retrieved from a HashMap
You can use ListOrderedMap from Apache's Commons-Collection library to keep the order.
How to sort (any kind of sorting) a key of a map(treemap or hashmap)
i have a problem and it goes like this.
i have a map that has a key of
27527-683,
27525-1179,
27525-1571,
27525-1813,
27525-4911,
27526-1303,
27526-3641,
27525-3989,
27525-4083,
27525-4670,
27526-4102,
27526-558,
27527-2411,
27527-4342
this is the list of keys and the value for each of the key is a list.
now, how can i sort this key in ascending order by number.
ex. if i want to sort : 1,2,11,20,31,3,10
i want to have as output is : 1,2,3,10,11,20,31
but when i use the autosort of treemap the output goes : 1,10,11,2,20,3,31
how can i sort it in ascending order by numeric?
please help me. i can't think of anymore ways because this is my first time handling map and list
Your keys are Strings. The natural ordering of strings is lexicographical. You either need to specify a custom comparator in the constructor of the TreeMap, or use an Integer key.
Furthermore, you can better represent a Map<Key, List<Value>> as a Google Guava Multimap, see for example SortedSetMultimap.
Continuing with the Guava example:
Multimap<Integer, Person> multimap = SortedSetMultimap.create(Ordering.natural(), Ordering.arbitrary());
multimap.put(1, x);
multimap.put(1, y);
multimap.put(2, z);
multimap.put(1, a);
Then
multimap.get(1) will return a set containing [x, y, a] in some arbitrary order.
multimap.keys() will return a sorted set of [1, 2].
Your keys are currently Strings, that you would appear to rather handle like Integers. You will need to reformulate how you handle the map object, as many people here have suggested (it may be the correct method). An easier method involves using that list of keys you have copied us in on.
I see there is a way to output the list of keys. Sort that however you like. Arrays and lists are easily sorted by built in commands from your runtime environment. You might have to first split those elements at the hyphen.
I'd recommend a book on Data Structures.
Use SortedMap, for example, java.util.TreeMap.
keyword : SortedMap
SortedMap<Integer, Integer> s = new TreeMap<Integer, Integer>();
s.put(1, 1);
s.put(4, 2);
s.put(2, 3);
System.out.println(s); //{1=1, 2=3, 4=2}
also look at this example
HashMap selections = new HashMap<Integer, Float>();
How can i get the Integer key of the 3rd smaller value of Float in all HashMap?
Edit
im using the HashMap for this
for (InflatedRunner runner : prices.getRunners()) {
for (InflatedMarketPrices.InflatedPrice price : runner.getLayPrices()) {
if (price.getDepth() == 1) {
selections.put(new Integer(runner.getSelectionId()), new Float(price.getPrice()));
}
}
}
i need the runner of the 3rd smaller price with depth 1
maybe i should implement this in another way?
Michael Mrozek nails it with his question if you're using HashMap right: this is highly atypical scenario for HashMap. That said, you can do something like this:
get the Set<Map.Entry<K,V>> from the HashMap<K,V>.entrySet().
addAll to List<Map.Entry<K,V>>
Collections.sort the list with a custom Comparator<Map.Entry<K,V>> that sorts based on V.
If you just need the 3rd Map.Entry<K,V> only, then a O(N) selection algorithm may suffice.
//after edit
It looks like selection should really be a SortedMap<Float, InflatedRunner>. You should look at java.util.TreeMap.
Here's an example of how TreeMap can be used to get the 3rd lowest key:
TreeMap<Integer,String> map = new TreeMap<Integer,String>();
map.put(33, "Three");
map.put(44, "Four");
map.put(11, "One");
map.put(22, "Two");
int thirdKey = map.higherKey(map.higherKey(map.firstKey()));
System.out.println(thirdKey); // prints "33"
Also note how I take advantage of Java's auto-boxing/unboxing feature between int and Integer. I noticed that you used new Integer and new Float in your original code; this is unnecessary.
//another edit
It should be noted that if you have multiple InflatedRunner with the same price, only one will be kept. If this is a problem, and you want to keep all runners, then you can do one of a few things:
If you really need a multi-map (one key can map to multiple values), then you can:
have TreeMap<Float,Set<InflatedRunner>>
Use MultiMap from Google Collections
If you don't need the map functionality, then just have a List<RunnerPricePair> (sorry, I'm not familiar with the domain to name it appropriately), where RunnerPricePair implements Comparable<RunnerPricePair> that compares on prices. You can just add all the pairs to the list, then either:
Collections.sort the list and get the 3rd pair
Use O(N) selection algorithm
Are you sure you're using hashmaps right? They're used to quickly lookup a value given a key; it's highly unusual to sort the values and then try to find a corresponding key. If anything, you should be mapping the float to the int, so you could at least sort the float keys and get the integer value of the third smallest that way
You have to do it in steps:
Get the Collection<V> of values from the Map
Sort the values
Choose the index of the nth smallest
Think about how you want to handle ties.
You could do it with the google collections BiMap, assuming that the Floats are unique.
If you regularly need to get the key of the nth item, consider:
using a TreeMap, which efficiently keeps keys in sorted order
then using a double map (i.e. one TreeMap mapping integer > float, the other mapping float > integer)
You have to weigh up the inelegance and potential risk of bugs from needing to maintain two maps with the scalability benefit of having a structure that efficiently keeps the keys in order.
You may need to think about two keys mapping to the same float...
P.S. Forgot to mention: if this is an occasional function, and you just need to find the nth largest item of a large number of items, you could consider implementing a selection algorithm (effectively, you do a sort, but don't actually bother sorting subparts of the list that you realise you don't need to sort because their order makes no difference to the position of the item you're looking for).