fetching ordered pair of values - java

I am looking to implement a data structure that would add / render an ordered pair of values. eg.
orderedPair.add(value1, text1)
orderedPair.add(value1, text2)
orderedPair.add(value2, text3, data1)
orderedPair.add(value2, data2)
orderedPair.add(value1, text5)
When I get, I want it to return iteratively as
value1, text1
value1, text2
value2, text3, data1 and so on.
LinkedHashMaps or any variants of HashMaps do not work since they return only the value based on key and what I am trying to get is value, value pairs. Note that neither value / text or data are unique and I may not be able to fetch it based on any keys. Also, i do NOT want a sorted list, I do need an ORDERED list only.
Question is: Is there any data structure in Java that can be used to accomplish this?
I did not come across any that serves this purpose. In which case I am pondering about writing a custom collection that would accomplish this. Any suggestions / help is welcome.

Wrapping the discussion in the comments into an answer, since it seems to be useful to the OP:
Create a class Tuple, which will be your pairs/triples.
Note that this class can be implemented with a fixed number of parameters or as a container that holds a list of objects.
Hold these Tuple objects in a List<Tuple>, and you are done.
You can also implement hashCode(), equals() and make it implement Comparable to this class - and you will be able to use it with other collections such as TreeSet and HashSet.

Just use a Map of Lists, like Treemap
Map<Integer, List<Integer>> content = new Treemap<Integer, List<Integer>>();
if (not content.containsKey(value1)) {
content.put(value1, new LinkedList<Integer>());
}
content.get(value1).add(text1)
This would be the function orderedPair.add
Then for output, traverse the Map and for each entry, write out each item of the corresponding List
Since you want to have it ordered, pass a Comparator to the Treemap constructor.

Related

Sort hasmap by value inside of a treemap

I have the following treemap
private TreeMap<Long, HashMap<Long, Entry>> index;
Entry contains:
int tf //count
ArrayList<long> off //positions
For each entry in the treemap, I would like to sort the hashmaps by tf. In the following picture, tf of [3] has a bigger value of tf of [0] so I would like to move it to be at the beggining. How can I do that?
You cannot order a HashMap. Trying to do so breaks the way a HashMap stores and finds the elements added to it
What you are trying to do here (as I understand it) is sorting the treemap by its value, while TreeMap can only sort by its keys. more details here - TreeMap sort by value
You may try writing your own sorting method and store the result of sort in a linkedHashMap instead of Treemap. That way you can be able to access the entries in the exact order you added that to the linkedHashMap.
Note: with each change happening to the original map, you ll need to sort it and move it to a different linkedHashMap. Which is very clumsy.
You may consider using different object model for your program.
I believe the fundamental problem with your question is that HashMaps are not sortable by definition. Secondly, a variable definition that is more generic may prove useful:
private SortedMap<Long, SortedMap<Entry, Long>> index;
Noticed I switched the order of Entry and Long. This is because Maps only sort based on the key. You'd have to either make Entry implement Comparable or provide a custom Comparator when you instantiate that Map.

combine two arraylist in one with certain order or a serial id

I couldn't find a better title than that so pardon me for any kind of confusion.
I want to combine two hashmap into one hashmap.I am actually using hashmaps to contain the datas of table where key=coloumName and value= coloumValues.
My code looks something like
HashMap<String, ArrayList> FTMap = table1.getColumn().getColumnValues()
HashMap<String, ArrayList> STMap = table2.getColumn().getColumnValues()
HashMap<String, ArrayList> FinalTableMap = new HashMap()
FinalTableMap.putAll(FTMap)
FinalTableMap.putAll(STMap)
I don't have any problem with column names but the order of coloumvalues are not working after the combining. Since i am using arraylist,i am trying to compare two arraylist and put it in a final arraylist which can be used as the value of the final hashmap.I need some advice or suggestion for this matching between two arraylist.
After you have used addAll to combine your lists, you can use Collections.sort(List, Comparator) to sort your ArrayList. In your Comparator's compare function, you will compare the two objects using the values you wish to sort by (you mentioned serial id?).
See Sort ArrayList of custom Objects by property for a brief example.

HashMap inside an Arraylist

ArrayList<HashMap<String, String>>
arrayListRowsFirst = new ArrayList<HashMap<String, String>>();
Today when i was going through a code, this piece of code struck me for a while. Here are some of my questions over this declaration.
What could be the requirement if one has to append an HashMap into an ArrayList.
What will happen during sorting of arraylist, how it will go, will it take long time.
First off, "generic chaining" in my opinion is a poor practice. I would encourage wrapping the HashMap in a class that encapsulates the data inside, allowing the logic for manipulation to be inside the class, not just strewn about everywhere.
To answer #1, I could think of a number of scenarios. You might have languages for instance, mapping certain constants to other translations. The fact that it says rows first in the identifier makes me think perhaps it's some kind of matrix of data, and that the first String parameter will exist in all the entries of the list (a poor practice indeed.)
Edit: I misunderstood your question, it appears. You would add it like any other entry. See the others' answers for example code. :-)
To answer #2, you won't be able to sort the ArrayList unless you are able to provide a comparator, at which point it's up to you how it's sorted (could be size, could be the value of a particular key, could be Math.random(), it's up to whoever writes the comparator).
There is no "special requirement" to append an HashMap to an ArrayList.
And as neither Map nor HashMap implements Comparable, so if you want to sort the ArrayList, you would have to create your own Comparator.
A sort on a List which contains Map would be exactly the same as a sort on a List wich contains anything else.
What do you mean about "append a HashMap into an ArrayList"? You add HashMaps to the ArrayList the way you add any object to a List
HashMap<String,String> hm = new HashMap<String,String>();
arrayListRowsFirst.add(hm);
You sort the array list like you sort any other - you would need to define a Comparator that compared two HashMaps, and use Collections.sort with that Comparator. How long it takes will depend a lot on how you're comparing the HashMaps.
You would add HashMaps to the ArrayList like you would any other object, using the add() method. Obviously it would need to be of the correct Type, in this case a HashMap of Strings.
You would need to create a comparator so that your HashMaps would be sortable.
The declaration should be
List<Map<String, String>>
1 to append a map into the list, you just do
Map<String, String> map = new HashMap<String, String>();
list.add(map);
2 To sort the list, you would need a way to tell if one Map is "greater than", "less than", or "equal" to another Map. The could or might not take a long time depending on your needs. It doesn't have to take a long time.

When to use a Map instead of a List in Java?

I didn't get the sense of Maps in Java. When is it recommended to use a Map instead of a List?
Say you have a bunch of students with names and student IDs. If you put them in a List, the only way to find the student with student_id = 300 is to look at each element of the list, one at a time, until you find the right student.
With a Map, you associate each student's ID and the student instance. Now you can say, "get me student 300" and get that student back instantly.
Use a Map when you need to pick specific members from a collection. Use a List when it makes no sense to do so.
Say you had exactly the same student instances but your task was to produce a report of all students' names. You'd put them in a List since there would be no need to pick and choose individual students and thus no need for a Map.
Java map: An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.
Java list: An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.
The difference is that they are different. Map is a mapping of key/values, a list of a list of items.
I thinks its a lot the question of how you want to access your data. With a map you can "directly" access your items with a known key, in a list you would have to search for it, evan if its sorted.
Compare:
List<MyObject> list = new ArrayList<MyObject>();
//Fill up the list
// Want to get object "peter"
for( MyObject m : list ) {
if( "peter".equals( m.getName() ) {
// found it
}
}
In a map you can just type
Map<String, MyObject> map = new HashMap<String, MyObject>();
// Fill map
MyObject getIt = map.get("peter");
If you have data to process and need to do it with all objects anyway, a list is what you want. If you want to process single objects with well known key, a map is better.
Its not the full answer (just my 2...) but I hope it might help you.
A map is used as an association of a key and a value. With a list you have basically only values.
The indexes in List are always int, whereas in Map you can have another Object as a key.
Resources :
sun.com - Introduction to the Collections Framework, Map
Depends on your performance concerns. A Map more explicitly a HashMap will guarantee O(1) on inserts and removes. A List has at worst O(n) to find an item. So if you would be so kind as to elaborate on what your scenario is we may help more.
Its probably a good idea to revise Random Access Vs Sequential Access Data Structures. They both have different run time complexities and suitable for different type of contexts.
When you want to map instead of list. The names of those interfaces have meaning, and you shouldn't ignore it.
Use a map when you want your data structure to represent a mapping for keys to values. Use a list when you want your data to be stored in an arbitrary, ordered format.
Map and List serve different purpose.
List holds collection of items. Ordered (you can get item by index).
Map holds mapping key -> value. E.g. map person to position: "JBeg" -> "programmer". And it is unordered. You can get value by key, but not by index.
Maps store data objects with unique keys,therefore provides fast access to stored objects. You may use ConcurrentHashMap in order to achieve concurrency in multi-threaded environments.
Whereas lists may store duplicate data and you have to iterate over the data elements in order to access a particular element, therefore provide slow access to stored objects.
You may choose any data structure depending upon your requirement.

Maintaining order of items in java

What is the best way to do the following(make sure that items from List are following the same order as those in ListTwo):
List
harry~20
marry~22
peter~40
jerry~33
janice~20
ListTwo
harry
marry
peter
janice
Now the result should look like this
ListThree
harry
marry
peter
janice
jerry
Step by step :
For each item in List :
compare first part of the item to item in ListTwo
if they are equal add it to ListThree
if item exist in List but not in ListTwo dont do anything yet save it
somewhere
continue from step 1
you are at the end of the List add the item(s) you skipped before in step
3
I know this much(actually I don't, I think I know), there are better ways to do this I'm sure
Why did I get downvote, did I miss something ?
It may be easier if you reverse the roles (store the keys in the ArrayList, in order) and the key-value mappings in a SortedMap, such as TreeMap, or ConcurrentSkipListMap. The comparator for the sorted map can use List.indexOf as the basis for element comparison.
With this arrangement, the map defines the key/value mapping, which is natural for the map, and the list maintains the desired order, which is quite natural for a List.
Alternatively, use a regular Map, and not a sorted map, and use iteration over the list, and fetching values from the map. E.g.
ArrayList keysList;
Map keyValues;
for(String key: keysList) {
String value = keyValues.get(key);
}
EDIT: Commons collections has SetUniqueList - a list that ensures uniqueness like a Set. It also has has various types of OrderedMap, in particular a ListOrderedMap that maintains the key/value mappings in the order of a list. For generics support, see commons collections with generics.
Use LinkedHashMap
You can call something like
map.put(one,value1);
and later call
map.get(one);
which will return value1
also a hash map does not accept duplicate key, so if you call
map.put(one,value2);
after this the original value is replaced.
you can use
map.containsKey(one)
to check whether one already exists as a key
If you are only comparing the keys of element then you can store them in LinkedHashSet and use the contains method of linkedHashset to check whether the element exists in constant time O(1).
LinkeHashMap also serves the purpose, however it requires extra space to store the value and this is not required we are only interested in keys.
Refer : http://docs.oracle.com/javase/6/docs/api/java/util/LinkedHashSet.html

Categories