views:

171

answers:

2

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 :

  1. compare first part of the item to item in ListTwo

  2. if they are equal add it to ListThree

  3. if item exist in List but not in ListTwo dont do anything yet save it somewhere

continue from step 1

  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 ?

+2  A: 

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.

mdma
@mdma thank you for your swift response, I forgot to mention that I can't have duplicate entries thats why I'm using the LinkedHashSet and order is important also.
c0mrade
@mdma can you elaborate on this 'The comparator for the sorted map can use List.indexOf as the basis for element comparison.'
c0mrade
@c0mrade - please see my edit. Commons collections has all the pieces to do this for you without having to write any custom comparators etc.
mdma
A: 

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

Louis Rhys