How to remove duplicate key-value pairings in a map - java

I'm stuck on how to transfer key-value pairs from map1 into map2 only if each key has a unique value in map1.
Let's say I have the following maps:
map1: [1,2] [2,4] [4,4]
map2: [1,2] [2,4]
I suppose the algorithm would be:
Loop through entries in the first map.
Add a key to map2.
Add a value to a set which checks against the values of map2
If the values are duplicate the value doesn't get added to the set and disregard adding its corresponding key to map2.
Code snippet:
public static <K,V> Map<K,V> unique (Map<K,V> m) {
Map<K,V> newMap = new ArrayMap<K,V>();
//Remember all values in the newMap.
Set<V> holding = new ArraySet<V>(newMap.values());
for (Map.Entry<K, V> graphEntry : m.entries()) {
//not sure.
}
return newMap;
}
Is my idea of how its supposed to be done on the right track? Quite lost here.

From a Map<K, V> create a Map<V, K> that will add the item if and only if the key is not in the map. Using this Map<V, K>, recreate your Map<K, V>.
public static <K, V> Map<K, V> createMap(Map<K, V> m) {
Map<K, V> map = new HashMap<K, V>();
Map<V, K> tmpMap = new HashMap<V, K>();
for(Map.Entry<K, V> entry : m.entrySet()) {
if (!tmpMap.containsKey(entry.getValue())) {
tmpMap.put(entry.getValue(), entry.getKey());
}
}
for(Map.Entry<V, K> entry : tmpMap.entrySet()) {
map.put(entry.getValue(), entry.getKey());
}
return map;
}
If you need to keep the preserver order of the data, use LinkedHashMap instead of HashMap.

Check out Guava BiMap.. This is what you need..
Although your problem is solved, you can take a look at the below code, to use Guava API for what you want to do: -
public void removeDuplicateValue() {
Map<Integer, String> existingMap = new HashMap<Integer, String>();
existingMap.put(1, "a");
existingMap.put(2, "b");
// Create a new BiMap
BiMap<Integer, String> biMap = HashBiMap.create();
for (Integer val: existingMap.keySet()) {
// forcePut will add a key-value pair, and overwrite the duplicate value.
biMap.forcePut(val, existingMap.get(val));
}
// Create Inverse Map for newly created BiMap.
BiMap<String, Integer> inverseBiMap = biMap.inverse();
for(String val: inverseBiMap.keySet()) {
System.out.println(val + ":" + biMap.get(val));
}
}

Try this one..
Map<String, String> myMap1 = new TreeMap<String, String>();
myMap1.put("1", "One");
myMap1.put("2", "Two");
myMap1.put("3", "One");
myMap1.put("4", "Three");
myMap1.put("5", "Two");
myMap1.put("6", "Three");
Set<String> mySet = new HashSet<String>();
for (Iterator itr = myMap1.entrySet().iterator(); itr.hasNext();)
{
Map.Entry<String, String> entrySet = (Map.Entry) itr.next();
String value = entrySet.getValue();
if (!mySet.add(value))
{
itr.remove();
}
}
Map<String, String> myMap2 = new TreeMap<String, String>(myMap1);
System.out.println("Result :"+myMap2);
Result :{1=One, 2=Two, 4=Three}

Related

sort descending linkedhashmap by value

i have 3 hashmap :
Map<String, HashMap<String, Integer>> tokenUnikTF= new LinkedHashMap<>();
Map<String, HashMap<String, Integer>> tokenUnikDF= new LinkedHashMap<>();
Map<String, HashMap<String, Double>> tokenUnikWeight= new LinkedHashMap<>();
the difference between the 3 hashmap above only in value, their key is the same.
here's how i add tokenUnikWeight's key and value :
for (String key5 : tokenUnikTF.keySet()) {
tokenUnikWeight.put(key5, calculateWeight());
}
i want to print them all together, but in descending order by tokenUnikWeight's value
here's my sorting code :
public static LinkedHashMap<String,Double> sortHashMap() {
List<Map.Entry<String, Double>> list = new LinkedList<>(tokenUnikWeight.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, Double>>() {
#Override
public int compare(Map.Entry<String, Double> o1, Map.Entry<String, Double> o2) {
return (o1.getValue()).compareTo(o2.getValue());
}
});
Map<String, Double> result = new LinkedHashMap<>();
for (Map.Entry<String, Double> entry : list) {
result.put(entry.getKey(), entry.getValue());
}
return (LinkedHashMap<String, Double>) result;
}
and here is my print code :
tokenUnikWeight = sortHashMap();
for (String key5 : tokenUnikWeight.keySet()) {
System.out.printf("%s - %d - %d - %f\n", key5, tokenUnikTF.get(key5), tokenUnikDF.get(key5), tokenUnikWeight.get(key5));
}
the output is i got null in some tf and df also my weight is sorted in ascending not descending :
someone help me please, i do lot of googling but still the same, it return null in some tf and df.
change your comparator to : return (o2.getValue()).compareTo(o1.getValue()); for descending order. As for null values, are you sure that those keys are present and their values are not null in tokenUnikTF, DF?
Try replacing (o1.getValue()).compareTo(o2.getValue()) with (o2.getValue()).compareTo(o1.getValue()) in your Comparator implementation.

how to merge more than one hashmaps also sum the values of same key in java

ı am trying to merge more than one hashmaps also sum the values of same key,
ı want to explain my problem with toy example as follows
HashMap<String, Integer> m = new HashMap<>();
HashMap<String, Integer> m2 = new HashMap<>();
m.put("apple", 2);
m.put("pear", 3);
m2.put("apple", 9);
m2.put("banana", 6);
ı tried putall
m.putAll(m2);
output is as follows
{banana=6, apple=9, pear=3}
but its result is not true for this problem.
ı want to output as
{banana=6, apple=11, pear=3}
how can ı get this result in java?
If you are using Java 8, you can use the new merge method of Map.
m2.forEach((k, v) -> m.merge(k, v, (v1, v2) -> v1 + v2));
This is a very nice use case for Java 8 streams. You can concatentate the streams of entries and then collect them in a new map:
Map<String, Integer> combinedMap = Stream.concat(m1.entrySet().stream(), m2.entrySet().stream())
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.summingInt(Map.Entry::getValue)));
There are lots of nice things about this solution, including being able to make it parallel, expanding to as many maps as you want and being able to trivial filter the maps if required. It also does not require the orginal maps to be mutable.
This method should do it (in Java 5+)
public static <K> Map<K, Integer> mergeAndAdd(Map<K, Integer>... maps) {
Map<K, Integer> result = new HashMap<>();
for (Map<K, Integer> map : maps) {
for (Map.Entry<K, Integer> entry : map.entrySet()) {
K key = entry.getKey();
Integer current = result.get(key);
result.put(key, current == null ? entry.getValue() : entry.getValue() + current);
}
}
return result;
}
Here's my quick and dirty implementation:
import java.util.HashMap;
import java.util.Map;
public class MapMerger {
public static void main(String[] args) {
HashMap<String, Integer> m = new HashMap<>();
HashMap<String, Integer> m2 = new HashMap<>();
m.put("apple", 2);
m.put("pear", 3);
m2.put("apple", 9);
m2.put("banana", 6);
final Map<String, Integer> result = (new MapMerger()).mergeSumOfMaps(m, m2);
System.out.println(result);
}
public Map<String, Integer> mergeSumOfMaps(Map<String, Integer>... maps) {
final Map<String, Integer> resultMap = new HashMap<>();
for (final Map<String, Integer> map : maps) {
for (final String key : map.keySet()) {
final int value;
if (resultMap.containsKey(key)) {
final int existingValue = resultMap.get(key);
value = map.get(key) + existingValue;
}
else {
value = map.get(key);
}
resultMap.put(key, value);
}
}
return resultMap;
}
}
Output:
{banana=6, apple=11, pear=3}
There are some things you should do (like null checking), and I'm not sure if it's the fastest. Also, this is specific to integers. I attempted to make one using generics of the Number class, but you'd need this method for each type (byte, int, short, longer, etc)
ı improve Lucas Ross's code. in stead of enter map by one by in function ı give all maps one times to function with arraylist of hashmap like that
public HashMap<String, Integer> mergeAndAdd(ArrayList<HashMap<String, Integer>> maplist) {
HashMap<String, Integer> result = new HashMap<>();
for (HashMap<String, Integer> map : maplist) {
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
Integer current = result.get(key);
result.put(key, current == null ? entry.getValue() : entry.getValue() + current);
}
}
return result;
}
}
it works too. thanks to everbody
Assume that you have many HashMaps: Map<String,Integer> map1, map2, map3;
Then you can use Java 8 streams:
Map<String,Integer> combinedMap = Stream.of(map1, map2, map3)
.flatMap(map -> map.entrySet().stream())
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.summingInt(Map.Entry::getValue)));
If the key exists, add to it's value. If not insert.
Here is a simple example which merges one map into another:
Foo oldVal = map.get(key);
if oldVal == null
{
map2.put(key, newVal);
}
else
{
map2.put(key, newVal + oldVal);
}
Obviously you have to loop over the first map so you can process all of it's entries but that's trivial.
Something like this should work:
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String map1_key = entry.getKey();
int map1_value = entry.getValue();
//check:
if(map2.get(map1_key)!=null){
int map2_value = map2.get(map1_key);
//merge:
map3.put(map1_key,map1_value+map2_value);
}else{
map3.put(map1_key,map1_value);
}
}
for (Map.Entry<String, Integer> entry2 : map2.entrySet()) {
String map2_key = entry2.getKey();
int map2_value = entry2.getValue();
//check:
if(map1.get(map2_key)!=null){
int map1_value = map1.get(map2_key);
//merge:
map3.put(map2_key,map1_value+map2_value);
}else{
map3.put(map2_key,map2_value);
}
}

How to compare two maps by both key and value and storing difference map in resultant map

Lets say I have two maps:
Map mapA = new HashMap();
Map mapB = new HashMap();
mapA.put("JEETENDRA", "24");
mapA.put("AHUJA", "24"); --1A
mapA.put("AHUJA", "25");---2A
mapA.put("PAL", "24");
mapB.put("AHUJA", "24");
mapB.put("JEETENDRA", "24");---1B
mapB.put("PAL", "24");
Now i want to compare both maps by both key and value since 2A and 1A have key common.
I know ideally its wrong since key should be unique for map but in code I am retrieving two column record and storing it as map.
MapA is before operations.
MapB is after some operations.
you can use this method, here I have used the Generics, and I have used one TreeMap with name result to hold all keys inside both HashMaps , from this method you will get all the matched objects in Hashmaps
public static <K extends Comparable<? super K>, V>
Map<K, Boolean> compareKeysAndValues(final Map<K, V> map1,
final Map<K, V> map2){
final Collection<K> allKeys = new HashSet<K>();
allKeys.addAll(map1.keySet());
allKeys.addAll(map2.keySet());
final Map<K, Boolean> result = new TreeMap<K, Boolean>();
for(final K key : allKeys){
result.put(key,
map1.containsKey(key) == map2.containsKey(key) &&
Boolean.valueOf(equal(map1.get(key), map2.get(key))));
}
return result;
}
and if you want to get the value which are different simply reverse the check in result.put function

Reversing a HashMap from Map<String, Boolean> to Map<Boolean, List<String>>

Is there a more elegant/built-in way to reverse the keys and values of a Hashmap?
I currently have the following.
private Map<Boolean, List<String>> reverseMap(Map<String, Boolean> permissions) {
List<String> allow = new ArrayList<String>();
List<String> deny = new ArrayList<String>();
Map<Boolean, List<String>> returnvalue = new HashMap<Boolean, List<String>>();
for (Entry<String, Boolean> entry : permissions.entrySet()) {
if(entry.getValue()) {
allow.add(entry.getKey());
} else {
deny.add(entry.getKey());
}
}
returnvalue.put(true, allow);
returnvalue.put(false, deny);
return returnvalue;
}
You might consider using one of Guava's Multimap implementations. For example:
private Multimap<Boolean, String> reverseMap(Map<String, Boolean> permissions) {
Multimap<Boolean, String> multimap = ArrayListMultimap.create();
for (Map.Entry<String, Boolean> entry : permissions.entrySet()) {
multimap.put(entry.getValue(), entry.getKey());
}
return multimap;
}
Or more generally:
private static <K, V> Multimap<V, K> reverseMap(Map<K, V> source) {
Multimap<V, K> multimap = ArrayListMultimap.create();
for (Map.Entry<K, V> entry : source.entrySet()) {
multimap.put(entry.getValue(), entry.getKey());
}
return multimap;
}
I'd do something similar (but if you must do this kind of thing frequently, consider Guava), only replacing the List with Set (seems a little more consistent) and prefilling the reversemap:
private Map<Boolean, Set<String>> reverseMap(Map<String, Boolean> permissions) {
Map<Boolean, Set<String>> returnvalue = new HashMap<Boolean, Set<String>>();
returnvalue.put(Boolean.TRUE, new HashSet<String>());
returnvalue.put(Boolean.FALSE, new HashSet<String>());
for (Entry<String, Boolean> entry : permissions.entrySet())
returnvalue.get(entry.getValue()).add(entry.getKey());
return returnvalue;
}
First thing to note is that you don't really need a reverse map if your values are only true or false. It will make sense if you have a broader range of values.
One easy (but not very elegant) way to get the entries with a specific value is:
public static <T, E> Set<T> getKeysByValue(Map<T, E> map, E value) {
Set<T> keys = new HashSet<T>();
for (Entry<T, E> entry : map.entrySet()) {
if (entry.getValue().equals(value)) {
keys.add(entry.getKey());
}
}
return keys;
}
You can see that this is not so good if you need to call it every now and then. It makes sense to have two different maps (straight and reverse) and add entries to both. You can't use Bidi maps since there is no 1:1 relation between keys and values.
UPDATE: The following solution won't work. See comments.
You can also consider using a TreeMap and keep it sorted based on the value. This way you can have a sorted set by calling map.entrySet() any time (denies entries first, then allows). The drawback is that it is only one set.
ValueComparator bvc = new ValueComparator(map);
TreeMap<String,Boolean> sorted_map = new TreeMap(bvc);
class ValueComparator implements Comparator {
Map base;
public ValueComparator(Map base) {
this.base = base;
}
public int compare(Object a, Object b) {
return (Boolean)base.get(a).compareTo((Boolean)base.get(b));
}
}
Guava's BiMap already provides a method for reversing its key-value pairs. Perhaps you could change the interface of the Map in question to BiMap, or else use the following code:
private BiMap<Boolean, String> reverseMap(Map<String, Boolean> permissions) {
BiMap<String, Boolean> bimap = HashBiMap.create(permissions);
return bimap.inverse();
}

How can I sort Map values by key in Java?

I have a Map that has strings for both keys and values.
The data is like the following:
"question1", "1"
"question9", "1"
"question2", "4"
"question5", "2"
I want to sort the map based on its keys. So, in the end, I will have question1, question2, question3, and so on.
Eventually, I am trying to get two strings out of this Map:
First String: Questions (in order 1 .. 10)
Second String: Answers (in the same order as the question)
Right now I have the following:
Iterator it = paramMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry) it.next();
questionAnswers += pairs.getKey() + ",";
}
This gets me the questions in a string, but they are not in order.
Short answer
Use a TreeMap. This is precisely what it's for.
If this map is passed to you and you cannot determine the type, then you can do the following:
SortedSet<String> keys = new TreeSet<>(map.keySet());
for (String key : keys) {
String value = map.get(key);
// do something
}
This will iterate across the map in natural order of the keys.
Longer answer
Technically, you can use anything that implements SortedMap, but except for rare cases this amounts to TreeMap, just as using a Map implementation typically amounts to HashMap.
For cases where your keys are a complex type that doesn't implement Comparable or you don't want to use the natural order then TreeMap and TreeSet have additional constructors that let you pass in a Comparator:
// placed inline for the demonstration, but doesn't have to be a lambda expression
Comparator<Foo> comparator = (Foo o1, Foo o2) -> {
...
}
SortedSet<Foo> keys = new TreeSet<>(comparator);
keys.addAll(map.keySet());
Remember when using a TreeMap or TreeSet that it will have different performance characteristics than HashMap or HashSet. Roughly speaking operations that find or insert an element will go from O(1) to O(Log(N)).
In a HashMap, moving from 1000 items to 10,000 doesn't really affect your time to lookup an element, but for a TreeMap the lookup time will be about 1.3 times slower (assuming Log2). Moving from 1000 to 100,000 will be about 1.6 times slower for every element lookup.
Assuming TreeMap is not good for you (and assuming you can't use generics):
List sortedKeys=new ArrayList(yourMap.keySet());
Collections.sort(sortedKeys);
// Do what you need with sortedKeys.
Using the TreeMap you can sort the map.
Map<String, String> map = new HashMap<>();
Map<String, String> treeMap = new TreeMap<>(map);
for (String str : treeMap.keySet()) {
System.out.println(str);
}
Just use TreeMap:
new TreeMap<String, String>(unsortMap);
Be aware that the TreeMap is sorted according to the natural ordering of its 'keys'.
Use a TreeMap!
If you already have a map and would like to sort it on keys, simply use:
Map<String, String> treeMap = new TreeMap<String, String>(yourMap);
A complete working example:
import java.util.HashMap;
import java.util.Set;
import java.util.Map;
import java.util.TreeMap;
import java.util.Iterator;
class SortOnKey {
public static void main(String[] args) {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("3", "three");
hm.put("1", "one");
hm.put("4", "four");
hm.put("2", "two");
printMap(hm);
Map<String, String> treeMap = new TreeMap<String, String>(hm);
printMap(treeMap);
} // main
public static void printMap(Map<String, String> map) {
Set s = map.entrySet();
Iterator it = s.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String key = (String) entry.getKey();
String value = (String) entry.getValue();
System.out.println(key + " => " + value);
} // while
System.out.println("========================");
} // printMap
} // class
Provided you cannot use TreeMap, in Java 8 we can make use of the toMap() method in Collectors which takes the following parameters:
keymapper: mapping function to produce keys
valuemapper: mapping function to produce values
mergeFunction: a merge function, used to resolve collisions between values associated with the same key
mapSupplier: a function which returns a new, empty Map into which the
results will be inserted.
Java 8 Example
Map<String, String> sample = new HashMap<>(); // Push some values to map
Map<String, String> newMapSortedByKey = sample.entrySet().stream()
.sorted(Map.Entry.<String, String>comparingByKey().reversed())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
Map<String, String> newMapSortedByValue = sample.entrySet().stream()
.sorted(Map.Entry.<String, String>comparingByValue().reversed())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
We can modify the example to use custom comparator and to sort based on keys as:
Map<String, String> newMapSortedByKey = sample.entrySet().stream()
.sorted((e1, e2) -> e1.getKey().compareTo(e2.getKey()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
Using Java 8:
Map<String, Integer> sortedMap = unsortMap.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
In Java 8
To sort a Map<K, V> by key, putting keys into a List<K>:
List<K> result = map.keySet().stream().sorted().collect(Collectors.toList());
To sort a Map<K, V> by key, putting entries into a List<Map.Entry<K, V>>:
List<Map.Entry<K, V>> result =
map.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toList());
Last but not least: to sort strings in a locale-sensitive manner - use a Collator (comparator) class:
Collator collator = Collator.getInstance(Locale.US);
collator.setStrength(Collator.PRIMARY); // case insensitive collator
List<Map.Entry<String, String>> result =
map.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey(collator))
.collect(Collectors.toList());
This code can sort a key-value map in both orders, i.e., ascending and descending.
<K, V extends Comparable<V>> Map<K, V> sortByValues
(final Map<K, V> map, int ascending)
{
Comparator<K> valueComparator = new Comparator<K>() {
private int ascending;
public int compare(K k1, K k2) {
int compare = map.get(k2).compareTo(map.get(k1));
if (compare == 0)
return 1;
else
return ascending*compare;
}
public Comparator<K> setParam(int ascending)
{
this.ascending = ascending;
return this;
}
}.setParam(ascending);
Map<K, V> sortedByValues = new TreeMap<K, V>(valueComparator);
sortedByValues.putAll(map);
return sortedByValues;
}
As an example:
Map<Integer, Double> recommWarrVals = new HashMap<Integer, Double>();
recommWarrVals = sortByValues(recommWarrVals, 1); // Ascending order
recommWarrVals = sortByValues(recommWarrVals, -1); // Descending order
List<String> list = new ArrayList<String>();
Map<String, String> map = new HashMap<String, String>();
for (String str : map.keySet()) {
list.add(str);
}
Collections.sort(list);
for (String str : list) {
System.out.println(str);
}
Just in case you don't want to use a TreeMap:
public static Map<Integer, Integer> sortByKey(Map<Integer, Integer> map) {
List<Map.Entry<Integer, Integer>> list = new ArrayList<>(map.entrySet());
list.sort(Comparator.comparingInt(Map.Entry::getKey));
Map<Integer, Integer> sortedMap = new LinkedHashMap<>();
list.forEach(e -> sortedMap.put(e.getKey(), e.getValue()));
return sortedMap;
}
Also, in case you wanted to sort your map on the basis of values, just change Map.Entry::getKey to Map.Entry::getValue.
In Java 8 you can also use .stream().sorted():
myMap.keySet().stream().sorted().forEach(key -> {
String value = myMap.get(key);
System.out.println("key: " + key);
System.out.println("value: " + value);
}
);
A good solution is provided here. We have a HashMap that stores values in unspecified order. We define an auxiliary TreeMap and we copy all data from HashMap into TreeMap using the putAll method. The resulting entries in the TreeMap are in the key-order.
Use the below tree map:
Map<String, String> sortedMap = new TreeMap<>(Comparator.comparingInt(String::length)
.thenComparing(Function.identity()));
Whatever you put in this sortedMap, it will be sorted automatically. First of all, TreeMap is sorted implementation of Map Interface.
There is a but as it sorts keys in the natural order fashion. As the Java documentation says, String type is a lexicographic natural order type. Imagine the below list of numbers with the String type. It means the below list will not be sorted as expected.
List<String> notSortedList = List.of("78","0", "24", "39", "4","53","32");
If you just use the default TreeMap constructor like below and push each element one-by-one like below:
Map<String, String> map = new TreeMap<>();
for (String s : notSortedList) {
map.put(s, s);
}
System.out.println(map);
The output is: {0=0, 14=14, 24=24, 32=32, 39=39, 4=4, 48=48, 53=53, 54=54, 78=78}
As you see, number 4, for example, comes after '39'. This is the nature of the lexicographic data types, like String. If that one was an Integer data type then that was okay though.
To fix this, use an argument to first check the length of the String and then compare them. In Java 8 it is done like this:
Map<String, String> sortedMap = new TreeMap<>(Comparator.comparingInt(String::length)
.thenComparing(Function.identity()));
It first compares each element by length then apply check by compareTo as the input the same as the element to compare with.
If you prefer to use a more understandable method, the above code will be equivalent with the below code:
Map<String, String> sortedMap = new TreeMap<>(
new Comparator() {
#Override
public int compare(String o1, String o2) {
int lengthDifference = o1.length() - o2.length();
if (lengthDifference != 0)
return lengthDifference;
return o1.compareTo(o2);
}
}
);
Because the TreeMap constructor accepts the comparator Interface, you can build up any an even more complex implementation of Composite classes.
This is also another form for a simpler version.
Map<String,String> sortedMap = new TreeMap<>(
(Comparator<String>) (o1, o2) ->
{
int lengthDifference = o1.length() - o2.length();
if (lengthDifference != 0)
return lengthDifference;
return o1.compareTo(o2);
}
);
Use LinkedHashMap, which provides the key ordering. It's also gives the same performance as HashMap. They both implement the Map interface, so you can just replace the initialization object HashMap to LinkedHashMap.
We can also sort the key by using Arrays.sort method.
Map<String, String> map = new HashMap<String, String>();
Object[] objArr = new Object[map.size()];
for (int i = 0; i < map.size(); i++) {
objArr[i] = map.get(i);
}
Arrays.sort(objArr);
for (Object str : objArr) {
System.out.println(str);
}

Categories

Resources