Sorting in Collections [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Can I sort two lists in relation to each other?
I have a Sorting Scenario, I didnt know how to acheive it?
Two Collections
List<<String>String> Key, List<<String>String> Value
I have to sort the value from a-z and such that the key for the corresponding value should not be change.
>>eg: Key and Value
2=>two
100=>four
1=>five
0=>nine
3=>eight
8=>one
>>after Sorting:
3=>eight
1=>five
100=>four
0=>nine
8=>one
2=>two
Any one please Help me?

Using a treemap with text as key ("two", "four"), we can order alphabetically and later retrieve the two lists again:
// Key contains ("2", "100", "1", ...)
// Value contains ("two", "four", "five", ...)
SortedMap<String, String> result = new TreeMap<String, String>();
// assuming the same size for both lists
for (int i = 0; i < Key.size(); i++) {
// when adding to TreeMap, keys are ordered automatically
result.put(Value.get(i), Key.get(i));
}
List<String> orderedKey = new ArrayList<String>(result.keySet());
List<String> orderedValue = new ArrayList<String>(result.values());
Hope this helps.

What about using a TreeMap? You have tuples of two corresponding entries and you are able to sort them as you wish.

Please check the information # http://paaloliver.wordpress.com/2006/01/24/sorting-maps-in-java/

Related

Go through multiple hashmaps of different sizes to extract values with common keys

So I essentially want to go through all the elements in the arraylist and match it with the keys of each hashmap and for the values of the common keys I want to make a new arraylist.
Essentially if keygrades is on value 1, I want to check every hashmap with the key 1 and then extract all the values associated with that key and make a brand new arraylist with those values.
ArrayList <String> keygrades = new ArrayList<>();
HashMap <String,String> gradeA = new HashMap<>();
HashMap <String,String> gradeB = new HashMap<>();
HashMap <String,String> gradeC = new HashMap<>();
HashMap <String,String> gradeD = new HashMap<>();
This is what is in the hashmap:
keygrades = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
gradeA = {11=134, 1=100, 3=110, 4=120, 15=142, 5=130}
gradeB = {2=102, 3=103, 6=108, 8=109}
gradeC = {3=104, 5=105, 6=111}
gradeD = {3=122, 4=123}
For example for key 1 I want a new arraylist which would be (100,"","","") ""= empty string. For key 2 I want a new arraylist which would be ("",102,"","").It would continue going through hashmaps in order and inputting into new arraylist each time.
I recommend writing a method with this struture:
Create an ArrayList<ArrayList>, which will hold the outcoming
ArrayLists containing the different values for common keys.
Iterate over Arraylist containing the keys.
Create an ArrayList that will get the 4 values.
Check all 4 Hashmaps with the current key using HashMap.get(key).
If the outcome is null, you should add "" to your ArrayList, otherwise you
enter the value to the ArrayList inside the loop.
After it iterated through the ArrayList containing the keys. You should have an
ArrayList<ArrayList> holding exactly as much ArrayList containing the values for similar keys, as you ArrayList of keys size.
You can achieve this by transforming your maps into a stream of maps and extracting the values for a particular key.
List<String> values = Stream.of(gradeA,
gradeB,
gradeC,
gradeD)
.map(map -> map.getOrDefault("1", ""))
.collect(Collectors.toList());
To reuse this, you'll have to create a function that handles the combining of the maps and a function that extracts values from that stream of maps.
The example should get you on your way.

How to merge duplicate key's value into existing key in java? [duplicate]

This question already has answers here:
HashMap with multiple values under the same key
(21 answers)
Closed 6 years ago.
Actually I have to merge duplicate key's value into existing key instead of replace, for that which map I have to use, I tried hashmap but it is replacing the values. Thanks...
Store them in a map, with each line of input append that to any existing value.
eg somthing like (sudo code)
Map map= new HashMap();
for (key,value) in inputdata
map.put(key, join(map.get(key),value));
Java8 Maps have a merge method that let's you modify the value associated to a given key if needed.
Suppose each value is a list (afterall if you want multiple values for a given key)...
List<Integer> l1 = new ArrayList<Integer>(); l1.add(1);
List<Integer> l2 = new ArrayList<Integer>(); l2.add(2);
List<Integer> l3 = new ArrayList<Integer>(); l3.add(3);
List<Integer> l4 = new ArrayList<Integer>(); l4.add(4);
BiFunction<Collection<Integer>,Collection<Integer>,Collection<Integer>> mergeFunc = (old,new)-> { old.addAll(new); return old; };
myMap.merge("one",l1,mergeFunc);
myMap.merge("two",l2,mergeFunc);
myMap.merge("three",l3,mergeFunc});
myMap.merge("one",l4,mergeFunc);

How do I store this data in Java?

I want a dictionary of values. The keys are all strings. Each key corresponds with some sort of list of strings. How do I make a list of strings for each key and update that accordingly? I'll explain:
I have a loop that is reading lines of a word list. The words are then converted into a string code and set as keys in the dictionary. Here is an example of the string code/word relationship.
123, [the]
456, [dog]
328, [bug]
...
However, my program keeps looping through the word list and eventually will run into a word with the same code as "the", but maybe a different word, lets say "cat". So I want the list to look like:
123, [the, cat]
456, [dog]
...
How do I get it to make an arraylist for every key that I can then add to on the fly when needed? My end goal is to be able to print out the list of words in that list for a called code (.get())
You can make a HashMap. In your case
HashMap<Integer, ArrayList<String>> works fine.
Like it has already been said, a MultiMap seems to be what you need. Guava that was already suggested and it's a good option. There is also and implementation from commons-collections you can use.
From commons-collections documentation:
MultiValuedMap<K, String> map = new MultiValuedHashMap<K, String>();
map.put(key, "A");
map.put(key, "B");
map.put(key, "C");
Collection<String> coll = map.get(key); // returns ["A", "B", "C"]
You can always implement your own MultiMap if you don't want to use an external library. Use a HashMap<String,List<String>> to store your values and wrap it with your own put, get and whatever other methods you see fit.
It sounds like you want a Multimap from the Guava library.
You can also go the route of using a Map<Integer, List<String>>, but then you will need to manually handle the case where the list is null (probably just allocate a new list in that case).
You can use a HashMap that links each id to a list of strings:
Map<String, List<String>> dictionary = new HashMap<String,List<String>>();
Now let's say you read two Strings: id and word . To add them to your dictionary, you can first verify if your id has already been read (using the containsKey() method)- in which case you just append the word to the list corresponding to that id - or, if this is not the case, you create a new list with this word:
//If the list already exists...
if(dictionary.containsKey(id)) {
List<String> appended = dictionary.get(id);
appended.add(word); //We add a new word to our current list
dictionary.remove(id); //We update the map by first removing the old list
dictionary.put(id, appended); //and then appending the new one
} else {
//Otherwise we create a new list for that id
List<String> newList = new ArrayList<String>();
newList.add(word);
dictionary.put(id, newList);
}
Then whenever you want to retrieve your list of strings for a certain id you can simply use dictionary.get(id);
You can find more information on HashMaps on the Java documentation
I assumed you didn't want repeats in your list so I used Set instead.
Map<String,Set<String>> mapToSet = new HashMap<>();
List<String []>keyvals = Arrays.asList(new String[][]{{"123","the"},{"123","cat"}});
for(String kv[] : keyvals) {
Set<String> s = mapToSet.get(kv[0]);
if(null == s) {
s = new HashSet<String>();
}
s.add(kv[1]);
mapToSet.put(kv[0], s);
}

Dynamically adding multiple values to a key in JAVA

I have multiple records received as string through a query. I want to store records having the same "long" key in a collection dynamically as I parse them in a loop. Like, insert key and value and if the key exists, it adds to the values and if not, a new key is created. What would be the most efficient way of doing this? I can do it using multiple arrays but I would prefer a cleaner way.
I cannot use a HashMap as I have to first store the records in an Array or ArrayList and then insert it which defeats the purpose as I have to group the lists by key first anyway. The no. of records will not more than 50 at a time.
E.g data:
for(i = 0; i < numRecords; i++ ) {
Data: 1 "A", 2 "B", 1 "C", 3 "D", 1 "E"
}
I want to have a collection where inside the loop I can just add: 1 "A" and so on..
I think Map<Long,List<String>> may help you.
Map<Long,List<String>> map = new HashMap<>();
...
if(map.get(key)!=null){
List<String> list = map.get(key);
list.add(value);
}else{
List<String> list = new ArrayList<>();
list.add(value);
map.put(key,list);
}

Java - Optimize finding a string in a list

I have an ArrayList of objects where each object contains a string 'word' and a date. I need to check to see if the date has passed for a list of 500 words. The ArrayList could contain up to a million words and dates. The dates I store as integers, so the problem I have is attempting to find the word I am looking for in the ArrayList.
Is there a way to make this faster? In python I have a dict and mWords['foo'] is a simple lookup without looping through the whole 1 million items in the mWords array. Is there something like this in java?
for (int i = 0; i < mWords.size(); i++) {
if ( word == mWords.get(i).word ) {
return mWords.get(i);
}
}
If the words are unique then use HashMap. I mean, {"a", 1}, {"b", 2}
Map<String, Integer> wordsAndDates = new HashMap<String, Integer>();
wordsAndDates.put("a", 1);
wordsAndDates.put("b", 2);
and wordsAndDates.get("a") return 1
If not you shouldn't use HashMap because it overrides previous value. I mean
wordsAndDates.put("a", 1);
wordsAndDates.put("b", 2);
wordsAndDates.put("a", 3);
and wordsAndDates.get("a") return 3
In such case you can use ArrayList and search in it
If you're not stuck with an ArrayList you should use some kind of hash based data structure. In this case it seems like a HashMap should fit nicely (it's pretty close to python's dict). This will give you an O(1) lookup time (compared to your current method of linear search).
You want to use a Map in Java
Map<String,Integer> mWords = new HashMap<String, Integer>();
mWords.put ("foo", 112345);
What about Collections.binarySearch() (NB: the list must be sorted) if ou are stuck with the ArrayList

Categories

Resources