I have a List of Map<String, String> that I want to iterate over and find the common elements inside the map of string and add to another map.
I am confused what should go inside the if loop to get my expected output. I am looking for comparator type call but I couldn't find that anywhere.
for (int i = 0; i < list.size() - 1; i++) {
if (list.get(i).get("Journal ID").equals(list.get(i+1).get("Journal ID")))
// ???
}
}
I was using this method to sort list of Maps. I am expecting some thing like this
public Comparator<Map<String, String>> mapComparator = new Comparator<>() {
public int compare(Map<String, String> m1, Map<String, String> m2) {
return m1.get("Journal ID").compareTo(m2.get("Journal ID"));
}
}
Collections.sort(list, mapComparator);
// input and the expected output
my List = [{Journal ID=123, featureID=312},{Journal ID=123, featureID=313},{Journal ID=134,
featureID=314},{Journal ID=123, featureID=1255}]
expected output is one that matching the "Journal ID" [{Journal ID=123, featureID=312},
{ Journal ID=123, featureID=313},{Journal ID=123, featureID=1255}].
One approach is to construct a second map which will aggregate all maps.
It will reflect all keys form all maps. As value will be a list of each key value with counters. Implementation can be enhanced also, but the main aspect is how to proceed. Having the aggregate map, then is straight forward to transform in what ever structure needed.
public class TestEqMap {
public static void main(String[] args)
{
Map<String, String> m1 = Map.of("a","a1","b","b1");
Map<String, String> m2 = Map.of("a","a1","b","b2");
Map<String, String> m3 = Map.of("a","a2","b","b2");
Map<String, String> m4 = Map.of("a","a1","b","b2");
Map<String, String> m5 = Map.of("a","a3","b","b2");
AggMap amap = new AggMap();
amap.addMap(m1);
amap.addMap(m2);
amap.addMap(m3);
amap.addMap(m4);
amap.addMap(m5);
amap.map.forEach((k,v)->System.out.println("key="+k+"\n"+v));
}
static class AggMap
{
public Map<String, ListItem> map = new HashMap<String,ListItem>();
public void addMap(Map<String,String> m)
{
for(String key: m.keySet())
{
if(this.map.containsKey(key))
{
this.map.get(key).addItem(m.get(key));
}
else
{
ListItem li = new ListItem();
li.addItem(m.get(key));
this.map.put(key, li);
}
}
}
}
static class ListItem
{
public List<Item> li = new ArrayList<Item>();
public ListItem() {};
public void addItem(String str)
{
for(Item i: this.li)
{
if(i.val.equals(str))
{
i.count++;
return;
}
}
this.li.add(new Item(str));
}
public String toString()
{
StringBuffer sb= new StringBuffer();
this.li.forEach(i->sb.append(i+"\n"));
return sb.toString();
}
}
static class Item
{
public String val;
public int count=1;
public Item(String val)
{
this.val = val;
}
public String toString()
{
return "val="+this.val+" count="+this.count;
}
}
}
Output:
key=a
val=a1 count=3
val=a2 count=1
val=a3 count=1
key=b
val=b1 count=1
val=b2 count=4
I have a TreeMap<Integer, TreeMap<int[][], Integer>> jungle. When I try to execute the statements
TreeMap<int[][], Integer> tempMap = new TreeMap();
int[][] matrix = {{1}};
tempMap.put(matrix, 4);
this last line gives me the
java.lang.ClassCastException: [[I cannot be cast to java.base/java.lang.Comparable at java.base/java.util.TreeMap.compare
exception. Am I not allowed to use an int[][] as a key in a treeMap?
The purpose of a TreeMap is to have an ordered collection
A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.
You must pass a Comparator that deals with int[][]; here an example with one that sorted based on the full sum of the array
class Custom2DArrayComparator implements Comparator<int[][]> {
private static int sum(int[][] v) {
return Arrays.stream(v).map(arr -> Arrays.stream(arr).sum())
.mapToInt(Integer::intValue).sum();
}
#Override
public int compare(int[][] o1, int[][] o2) {
return Integer.compare(sum(o1), sum(o2));
}
}
Use
public static void main(String[] args) {
TreeMap<int[][], Integer> tempMap = new TreeMap<>(new Custom2DArrayComparator());
int[][] matrix = {{1}};
tempMap.put(matrix, 4);
}
You can use the anonymous class to avoid creating a one outside
public static void main(String[] args) {
TreeMap<int[][], Integer> tempMap = new TreeMap<>(new Comparator<>() {
#Override
public int compare(int[][] o1, int[][] o2) {
return Integer.compare(sum(o1), sum(o2));
}
int sum(int[][] v) {
return Arrays.stream(v).map(arr -> Arrays.stream(arr).sum())
.mapToInt(Integer::intValue).sum();
}
});
int[][] matrix = {{1}};
tempMap.put(matrix, 4);
}
You'll need to implement your own logic in order for your key to be Comparable, as Johannes' comment points out. You could create a class that implements Comparator and pass it as argument at the initialization of the TreeMap.
Note that the default/overriden compare method would also be valid, as arrays are just Objects.
You could even implement all the logics for non-comparable Object keys you wish to insert in different Maps in a single class:
public class NonCompObjectKeyComparator implements Comparator<Object>
{
#Override
public int compare(Object o1, Object o2)
{
if (o1 instanceof int[][])
{
//((int[][])o1),((int[][])o2)//
}
else if (o1 instanceof String[])
{
//((String[])o1),((String[])o2)//
}
else if (o1 instanceof <OtherNonComparableObjType>)
{
//...
}
//...
return 0;
}
}
And then you got your überComparator there:
Comparator<Object> maCompa = new NonCompObjectKeyComparator();
TreeMap<int[][], Integer> tempMap = new TreeMap(maCompa);
TreeMap<String[], String> sArrayMap = new TreeMap(maCompa);
int[][] matrix = {{1}};
tempMap.put(matrix, 4);
String[] sKey = {"a"};
sArrayMap.put(sKey, "anotherWierdMap");
In order to create an specific int[][] comparator, just:
public class CustomKeyComparator implements Comparator<int[][]> {
public int compare(int[][] a1, int[][] a2) {
//your logic here
return 0;
}
}
and
TreeMap<int[][], Integer> tempMap = new TreeMap(new CustomKeyComparator());
int[][] matrix = {{1}};
tempMap.put(matrix, 4);
I have a HashMap with the following structure,
{val1#val2=val3#val4-val5}
where key = val1#val2 and value=val3#val4-val5 ,
HashMap<String, String> h = new HashMap<String, String>();
h.put("aaa#bbb", "111#444-555");
h.put("bbb#aaa", "222#ddd-222");
h.put("111#999", "000#213-aaa");
I have three conditions where I have to sort the map as,
1. By val1.
2. By val2.
3. By val3.
HashMaps don't guarantee order, in order to get sorted map you need to use LinkedHashMap.
To sort the keys you could use the java stream api, sort the map entries and the insert them in LinkedHashMap.
Map<String, String> h = new HashMap<>();
h.put("aaa#bbb", "111#444-555");
h.put("bbb#aaa", "222#ddd-222");
h.put("111#999", "000#213-aaa");
LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
h.entrySet().stream()
.sorted(Comparator.comparing(e -> e.getKey().split("#")[0]))// sort by val1
.sorted(Comparator.comparing(e -> e.getKey().split("#")[1]))// sort by val2
.sorted(Comparator.comparing(e -> e.getValue().split("#")[0]))// sort by val3
.forEach(e -> {
linkedHashMap.put(e.getKey(), e.getValue());
});
This should work:
public static void main(String[] args) {
LinkedHashMap<String, String> map = new LinkedHashMap<>();
map.put("aa#bb", "11111#44-5555555");
map.put("bb#aa", "22222#ddd-222");
map.put("11#99", "00000#213-aaa");
Function<Map.Entry<String, String>, String> byVal1 =
entry -> entry.getKey().substring(0, entry.getKey().indexOf('#'));
Function<Map.Entry<String, String>, String> byVal2 =
entry -> entry.getKey().substring(entry.getKey().indexOf('#') + 1);
Function<Map.Entry<String, String>, String> byVal3 =
entry -> entry.getValue().substring(0, entry.getValue().indexOf('#'));
// Just change this value to sort by a different value
Function<Map.Entry<String, String>, String> value = byVal3;
List<Map.Entry<String, String>> asList = map.entrySet().stream().sorted(Comparator.comparing(value)).collect(Collectors.toList());
map.clear();
asList.forEach(entry -> map.put(entry.getKey(), entry.getValue()));
map.entrySet().stream().forEach(entry -> System.out.println(entry));
}
You of course don't have to create the byValX functions in the method and could use method references instead.
No idea if that is what you want to accomplish (clarify what needs to be done and I can adapt the solution), but you can use a TreeMap:
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
public class TestDictionary {
public static void main(String[] args) {
Map<Key, Object> map = new TreeMap<>(new Comparator<Key>() {
#Override
public int compare(Key o1, Key o2) {
// do whatever you want here
return 0;
}
});
map.put(new Key("a", "b", "c"), new Value());
map.put(new Key("b", "c", "a"), new Value());
map.put(new Key("c", "b", "a"), new Value());
System.out.println(map);
}
static class Key {
String val1;
String val2;
String val3;
public Key(String val1, String val2, String val3) {
this.val1 = val1;
this.val2 = val2;
this.val3 = val3;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Key key = (Key) o;
return val1.equals(key.val1) &&
val2.equals(key.val2) &&
val3.equals(key.val3);
}
#Override
public int hashCode() {
return Objects.hash(val1, val2, val3);
}
}
static class Value {
int number;
}
}
I have the following HashMap:
Map<String, Integer> map = new HashMap<>();
How can I sum up all the integers for the duplicates String? or is there a better way to do it using Set?
for example, if I add these elements:
car 100
TV 140
car 5
charger 10
TV 10
I want the list to have:
car 105
TV 150
charger 10
I believe your question is: how do I put key/value pairs into a map in a way that changes the value rather than replacing it, for the same key.
Java has a Map method specifically for this purpose:
map.merge(key, value, (v, n) -> v + n);
This will add the value if the key isn't in the map. Otherwise it'll replace the current value with the sum of the current and new values.
The merge method was introduced in Java 8.
First of all you cannot add duplicate keys in map.
But if I understood what you want, the below code may help you:
if (map.containsKey(key))
map.put(key, map.get(key) + newValue);
else
map.put(key, newValue);
For java-8 and higher
You may just want to use the Map#merge method. It is the easiest way possible. If the key does not exist, it will add it, if it does exist, it will perform the merge operation.
map.merge("car", 100, Integer::sum);
map.merge("car", 20, Integer::sum);
System.out.println(map); // {car=120}
When you add "TV" for the second time, the first value (140) will be override because you cannot have duplicated keys on Map implementation. If you want to increment the value you will need to check if the key "TV" already exists and then increment/add the value.
For example:
if (map.containsKey(key)) {
value += map.get(key);
}
map.put(key, value)
HashMap dosen't save duplicates keys!
You can extend the HashMap Class(JAVA >= 8):
public class MyHashMap2 extends HashMap<String, Integer>{
#Override
public Integer put(String key, Integer value) {
return merge(key, value, (v, n) -> v + n);
}
public static void main (String[] args) throws java.lang.Exception
{
MyHashMap2 list3=new MyHashMap2();
list3.put("TV", 10);
list3.put("TV", 20);
System.out.println(list3);
}
}
Or You can aggregate the HashMap and replace the put method to add to the previous value the new value.
HashMap<String, Integer> list = new HashMap<>();
list.put("TV", 10);
list.put("TV", 20);
System.out.println(list);
MyHashMap list2 = new MyHashMap();
list2.put("TV", 10);
list2.put("TV", 20);
System.out.println(list2);
//OUTPUT:
//{TV=20}
//MyHashMap [List={TV=30}]
public class MyHashMap implements Map<String, Integer>{
HashMap<String, Integer> list = new HashMap<>();
public MyHashMap() {
super();
}
#Override
public int size() {
return list.size();
}
#Override
public boolean isEmpty() {
return list.isEmpty();
}
#Override
public boolean containsKey(Object key) {
return list.containsKey(key);
}
#Override
public boolean containsValue(Object value) {
return list.containsValue( value);
}
#Override
public Integer get(Object key) {
return list.get(key);
}
#Override
public Integer put(String key, Integer value) {
if(list.containsKey(key))
list.put(key, list.get(key)+value);
else
list.put(key, value);
return value;
}
#Override
public Integer remove(Object key) {
return list.remove(key);
}
#Override
public void putAll(Map<? extends String, ? extends Integer> m) {
list.putAll(m);
}
#Override
public void clear() {
list.clear();
}
#Override
public Set<String> keySet() {
return list.keySet();
}
#Override
public Collection<Integer> values() {
return list.values();
}
#Override
public Set<java.util.Map.Entry<String, Integer>> entrySet() {
return list.entrySet();
}
#Override
public String toString() {
return "MyHashMap [list=" + list + "]";
}
}
you can try the code here:https://ideone.com/Wl4Arb
This question already has answers here:
Sort a Map<Key, Value> by values
(64 answers)
Closed 6 years ago.
I need to sort my HashMap according to the values stored in it. The HashMap contains the contacts name stored in phone.
Also I need that the keys get automatically sorted as soon as I sort the values, or you can say the keys and values are bound together thus any changes in values should get reflected in keys.
HashMap<Integer,String> map = new HashMap<Integer,String>();
map.put(1,"froyo");
map.put(2,"abby");
map.put(3,"denver");
map.put(4,"frost");
map.put(5,"daisy");
Required output:
2,abby;
5,daisy;
3,denver;
4,frost;
1,froyo;
A generic version of a method to sort a Map resembles:
private static <K extends Comparable<K>, V extends Comparable<V>> Map<K, V> sort(
final Map<K, V> unsorted,
final boolean order) {
final var list = new LinkedList<>(unsorted.entrySet());
list.sort((o1, o2) -> order
? o1.getValue().compareTo(o2.getValue()) == 0
? o1.getKey().compareTo(o2.getKey())
: o1.getValue().compareTo(o2.getValue())
: o2.getValue().compareTo(o1.getValue()) == 0
? o2.getKey().compareTo(o1.getKey())
: o2.getValue().compareTo(o1.getValue()));
return list.stream().collect(
Collectors.toMap(
Entry::getKey, Entry::getValue, (a, b) -> b, LinkedHashMap::new
)
);
}
The following code offers ascending and descending sorting by value:
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class SortMapByValue
{
public static final boolean ASC = true;
public static final boolean DESC = false;
public static void main(String[] args)
{
// Creating dummy unsorted map
Map<String, Integer> unsortMap = new HashMap<String, Integer>();
unsortMap.put("B", 55);
unsortMap.put("A", 80);
unsortMap.put("D", 20);
unsortMap.put("C", 70);
System.out.println("Before sorting......");
printMap(unsortMap);
System.out.println("After sorting ascending order......");
Map<String, Integer> sortedMapAsc = sortByComparator(unsortMap, ASC);
printMap(sortedMapAsc);
System.out.println("After sorting descindeng order......");
Map<String, Integer> sortedMapDesc = sortByComparator(unsortMap, DESC);
printMap(sortedMapDesc);
}
private static Map<String, Integer> sortByComparator(Map<String, Integer> unsortMap, final boolean order)
{
List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(unsortMap.entrySet());
// Sorting the list based on values
Collections.sort(list, new Comparator<Entry<String, Integer>>()
{
public int compare(Entry<String, Integer> o1,
Entry<String, Integer> o2)
{
if (order)
{
return o1.getValue().compareTo(o2.getValue());
}
else
{
return o2.getValue().compareTo(o1.getValue());
}
}
});
// Maintaining insertion order with the help of LinkedList
Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
for (Entry<String, Integer> entry : list)
{
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
public static void printMap(Map<String, Integer> map)
{
for (Entry<String, Integer> entry : map.entrySet())
{
System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
}
}
}
Using newer Java features:
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;
public class SortMapByValue
{
private static final boolean ASC = true;
private static final boolean DESC = false;
public static void main(String[] args)
{
// Creating dummy unsorted map
Map<String, Integer> unsortMap = new HashMap<>();
unsortMap.put("B", 55);
unsortMap.put("A", 20);
unsortMap.put("D", 20);
unsortMap.put("C", 70);
System.out.println("Before sorting......");
printMap(unsortMap);
System.out.println("After sorting ascending order......");
Map<String, Integer> sortedMapAsc = sortByValue(unsortMap, ASC);
printMap(sortedMapAsc);
System.out.println("After sorting descending order......");
Map<String, Integer> sortedMapDesc = sortByValue(unsortMap, DESC);
printMap(sortedMapDesc);
}
private static Map<String, Integer> sortByValue(Map<String, Integer> unsortMap, final boolean order)
{
List<Entry<String, Integer>> list = new LinkedList<>(unsortMap.entrySet());
// Sorting the list based on values
list.sort((o1, o2) -> order ? o1.getValue().compareTo(o2.getValue()) == 0
? o1.getKey().compareTo(o2.getKey())
: o1.getValue().compareTo(o2.getValue()) : o2.getValue().compareTo(o1.getValue()) == 0
? o2.getKey().compareTo(o1.getKey())
: o2.getValue().compareTo(o1.getValue()));
return list.stream().collect(Collectors.toMap(Entry::getKey, Entry::getValue, (a, b) -> b, LinkedHashMap::new));
}
private static void printMap(Map<String, Integer> map)
{
map.forEach((key, value) -> System.out.println("Key : " + key + " Value : " + value));
}
}
In Java 8:
Map<Integer, String> sortedMap =
unsortedMap.entrySet().stream()
.sorted(Entry.comparingByValue())
.collect(Collectors.toMap(Entry::getKey, Entry::getValue,
(e1, e2) -> e1, LinkedHashMap::new));
Assuming Java, you could sort hashmap just like this:
public LinkedHashMap<Integer, String> sortHashMapByValues(
HashMap<Integer, String> passedMap) {
List<Integer> mapKeys = new ArrayList<>(passedMap.keySet());
List<String> mapValues = new ArrayList<>(passedMap.values());
Collections.sort(mapValues);
Collections.sort(mapKeys);
LinkedHashMap<Integer, String> sortedMap =
new LinkedHashMap<>();
Iterator<String> valueIt = mapValues.iterator();
while (valueIt.hasNext()) {
String val = valueIt.next();
Iterator<Integer> keyIt = mapKeys.iterator();
while (keyIt.hasNext()) {
Integer key = keyIt.next();
String comp1 = passedMap.get(key);
String comp2 = val;
if (comp1.equals(comp2)) {
keyIt.remove();
sortedMap.put(key, val);
break;
}
}
}
return sortedMap;
}
Just a kick-off example. This way is more useful as it sorts the HashMap and keeps the duplicate values as well.
map.entrySet().stream()
.sorted((k1, k2) -> -k1.getValue().compareTo(k2.getValue()))
.forEach(k -> System.out.println(k.getKey() + ": " + k.getValue()));
You don't, basically. A HashMap is fundamentally unordered. Any patterns you might see in the ordering should not be relied on.
There are sorted maps such as TreeMap, but they traditionally sort by key rather than value. It's relatively unusual to sort by value - especially as multiple keys can have the same value.
Can you give more context for what you're trying to do? If you're really only storing numbers (as strings) for the keys, perhaps a SortedSet such as TreeSet would work for you?
Alternatively, you could store two separate collections encapsulated in a single class to update both at the same time?
package com.naveen.hashmap;
import java.util.*;
import java.util.Map.Entry;
public class SortBasedonValues {
/**
* #param args
*/
public static void main(String[] args) {
HashMap<String, Integer> hm = new HashMap<String, Integer>();
hm.put("Naveen", 2);
hm.put("Santosh", 3);
hm.put("Ravi", 4);
hm.put("Pramod", 1);
Set<Entry<String, Integer>> set = hm.entrySet();
List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(
set);
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1,
Map.Entry<String, Integer> o2) {
return o2.getValue().compareTo(o1.getValue());
}
});
for (Entry<String, Integer> entry : list) {
System.out.println(entry.getValue());
}
}
}
As a kind of simple solution you can use temp TreeMap if you need just a final result:
TreeMap<String, Integer> sortedMap = new TreeMap<String, Integer>();
for (Map.Entry entry : map.entrySet()) {
sortedMap.put((String) entry.getValue(), (Integer)entry.getKey());
}
This will get you strings sorted as keys of sortedMap.
I extends a TreeMap and override entrySet() and values() methods. Key and value need to be Comparable.
Follow the code:
public class ValueSortedMap<K extends Comparable, V extends Comparable> extends TreeMap<K, V> {
#Override
public Set<Entry<K, V>> entrySet() {
Set<Entry<K, V>> originalEntries = super.entrySet();
Set<Entry<K, V>> sortedEntry = new TreeSet<Entry<K, V>>(new Comparator<Entry<K, V>>() {
#Override
public int compare(Entry<K, V> entryA, Entry<K, V> entryB) {
int compareTo = entryA.getValue().compareTo(entryB.getValue());
if(compareTo == 0) {
compareTo = entryA.getKey().compareTo(entryB.getKey());
}
return compareTo;
}
});
sortedEntry.addAll(originalEntries);
return sortedEntry;
}
#Override
public Collection<V> values() {
Set<V> sortedValues = new TreeSet<>(new Comparator<V>(){
#Override
public int compare(V vA, V vB) {
return vA.compareTo(vB);
}
});
sortedValues.addAll(super.values());
return sortedValues;
}
}
Unit Tests:
public class ValueSortedMapTest {
#Test
public void basicTest() {
Map<String, Integer> sortedMap = new ValueSortedMap<>();
sortedMap.put("A",3);
sortedMap.put("B",1);
sortedMap.put("C",2);
Assert.assertEquals("{B=1, C=2, A=3}", sortedMap.toString());
}
#Test
public void repeatedValues() {
Map<String, Double> sortedMap = new ValueSortedMap<>();
sortedMap.put("D",67.3);
sortedMap.put("A",99.5);
sortedMap.put("B",67.4);
sortedMap.put("C",67.4);
Assert.assertEquals("{D=67.3, B=67.4, C=67.4, A=99.5}", sortedMap.toString());
}
}
found a solution but not sure the performance if the map has large size, useful for normal case.
/**
* sort HashMap<String, CustomData> by value
* CustomData needs to provide compareTo() for comparing CustomData
* #param map
*/
public void sortHashMapByValue(final HashMap<String, CustomData> map) {
ArrayList<String> keys = new ArrayList<String>();
keys.addAll(map.keySet());
Collections.sort(keys, new Comparator<String>() {
#Override
public int compare(String lhs, String rhs) {
CustomData val1 = map.get(lhs);
CustomData val2 = map.get(rhs);
if (val1 == null) {
return (val2 != null) ? 1 : 0;
} else if (val1 != null) && (val2 != null)) {
return = val1.compareTo(val2);
}
else {
return 0;
}
}
});
for (String key : keys) {
CustomData c = map.get(key);
if (c != null) {
Log.e("key:"+key+", CustomData:"+c.toString());
}
}
}
package SortedSet;
import java.util.*;
public class HashMapValueSort {
public static void main(String[] args){
final Map<Integer, String> map = new HashMap<Integer,String>();
map.put(4,"Mango");
map.put(3,"Apple");
map.put(5,"Orange");
map.put(8,"Fruits");
map.put(23,"Vegetables");
map.put(1,"Zebra");
map.put(5,"Yellow");
System.out.println(map);
final HashMapValueSort sort = new HashMapValueSort();
final Set<Map.Entry<Integer, String>> entry = map.entrySet();
final Comparator<Map.Entry<Integer, String>> comparator = new Comparator<Map.Entry<Integer, String>>() {
#Override
public int compare(Map.Entry<Integer, String> o1, Map.Entry<Integer, String> o2) {
String value1 = o1.getValue();
String value2 = o2.getValue();
return value1.compareTo(value2);
}
};
final SortedSet<Map.Entry<Integer, String>> sortedSet = new TreeSet(comparator);
sortedSet.addAll(entry);
final Map<Integer,String> sortedMap = new LinkedHashMap<Integer, String>();
for(Map.Entry<Integer, String> entry1 : sortedSet ){
sortedMap.put(entry1.getKey(),entry1.getValue());
}
System.out.println(sortedMap);
}
}
public static TreeMap<String, String> sortMap(HashMap<String, String> passedMap, String byParam) {
if(byParam.trim().toLowerCase().equalsIgnoreCase("byValue")) {
// Altering the (key, value) -> (value, key)
HashMap<String, String> newMap = new HashMap<String, String>();
for (Map.Entry<String, String> entry : passedMap.entrySet()) {
newMap.put(entry.getValue(), entry.getKey());
}
return new TreeMap<String, String>(newMap);
}
return new TreeMap<String, String>(passedMap);
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
public class CollectionsSort {
/**
* #param args
*/`enter code here`
public static void main(String[] args) {
// TODO Auto-generated method stub
CollectionsSort colleciotns = new CollectionsSort();
List<combine> list = new ArrayList<combine>();
HashMap<String, Integer> h = new HashMap<String, Integer>();
h.put("nayanana", 10);
h.put("lohith", 5);
for (Entry<String, Integer> value : h.entrySet()) {
combine a = colleciotns.new combine(value.getValue(),
value.getKey());
list.add(a);
}
Collections.sort(list);
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
public class combine implements Comparable<combine> {
public int value;
public String key;
public combine(int value, String key) {
this.value = value;
this.key = key;
}
#Override
public int compareTo(combine arg0) {
// TODO Auto-generated method stub
return this.value > arg0.value ? 1 : this.value < arg0.value ? -1
: 0;
}
public String toString() {
return this.value + " " + this.key;
}
}
}