sort descending linkedhashmap by value - java

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.

Related

How to print HashMap values in descending order, but if two or more values are equal, print them by keys ascending? (JAVA)

For example we have
Map<String, Integer> map = new HashMap<>();
map.put("fragments", 5);
map.put("motes", 3);
map.put("shards", 5);
I want to print them like this:
fragments: 5
shards: 5
motes: 3
I would solve this by first putting the values in a TreeMap
Then I would sort the keys based on equal values and put them in a
LinkedHashMap to preserve the order.
Map<String, Integer> map = new TreeMap<>();
map.put("motes", 3);
map.put("shards", 5);
map.put("fragments", 5);
map = map.entrySet().stream().sorted(Comparator.comparing(
Entry<String, Integer>::getValue).reversed()).collect(
LinkedHashMap<String, Integer>::new,
(map1, e) -> map1.put(e.getKey(), e.getValue()),
LinkedHashMap::putAll);
map.entrySet().forEach(System.out::println);
Based on the excellent answer here, consider the following solution:
public static void main(String[] args) {
final Map<String, Integer> originalMap = new HashMap<>();
originalMap.put("fragments", 5);
originalMap.put("motes", 3);
originalMap.put("shards", 5);
final Map<String, Integer> sortedMap = sortByValue(originalMap, false);
sortedMap
.entrySet()
.stream()
.forEach((entry) -> System.out.println(entry.getKey() + " : " + entry.getValue()));
}
private static Map<String, Integer> sortByValue(Map<String, Integer> unsortedMap, final boolean ascending) {
List<Entry<String, Integer>> list = new LinkedList<>(unsortedMap.entrySet());
// Sorting the list based on values
list.sort((o1, o2) -> ascending ? 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));
}

How to get data (key,value) from ListArray

I use the code to Sort the data in the map.
Map<Integer, Integer> map = new HashMap<>();
List list = new ArrayList(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
#Override
public int compare(Map.Entry<Integer, Integer> a, Map.Entry<Integer, Integer> b) {
return a.getValue() - b.getValue();
}
});
I just copy the data from map to List and sort it.
How can I get the data from the List? The method get() of list returns just the object, not my 2 integers
You do that :
List list = new ArrayList(map.entrySet());
You could use generics in your list and then iterate on the Entry of the list after your sorted it:
List<Entry<Integer, Integer>> list = new ArrayList(map.entrySet());
...
// your sort the list
..
// you iterate on key-value
for (Entry<Integer, Integer> entry : list){
Integer key = entry.getKey();
Integer value = entry.getValue();
}
Your list actually contains elements of type Map.Entry<Integer, Integer>, so you can retrieve the each Entry as shown below:
Map<Integer, Integer> map = new HashMap<>();
//add the values to map here
//Always prefer to use generic types shown below (instead of raw List)
List<Map.Entry<Integer, Integer>> list = new ArrayList<>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
#Override
public int compare(Map.Entry<Integer, Integer> a,
Map.Entry<Integer, Integer> b){
return a.getValue() - b.getValue();
}
});
//loop over the list to retrieve the list elements
for(Map.Entry<Integer, Integer> entry : list) {
System.out.println(entry.getValue());
}

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);
}
}

What's the best way to sum two Map<String,String>?

I have the following maps.
Map<String,String> map1= new HashMap<String, String>(){{
put("no1","123"); put("no2","5434"); put("no5","234");}};
Map<String,String> map1 = new HashMap<String, String>(){{
put("no1","523"); put("no2","234"); put("no3","234");}};
sum(map1, map2);
I want to join them to one, summing up similar keyed values together. What;s the best way I could do it using java 7 or guava libraries ?
expected output
Map<String, String> output = { { "no1" ,"646"}, { "no2", "5668"}, {"no5","234"}, {"no3","234" } }
private static Map<String, String> sum(Map<String, String> map1, Map<String, String> map2) {
Map<String, String> result = new HashMap<String, String>();
result.putAll(map1);
for (String key : map2.keySet()) {
String value = result.get(key);
if (value != null) {
Integer newValue = Integer.valueOf(value) + Integer.valueOf(map2.get(key));
result.put(key, newValue.toString());
} else {
result.put(key, map2.get(key));
}
}
return result;
}
try this
Map<String, List<String>> map3 = new HashMap<String, List<String>>();
for (Entry<String, String> e : map1.entrySet()) {
List<String> list = new ArrayList<String>();
list.add(e.getValue());
String v2 = map2.remove(e.getKey());
if (v2 != null) {
list.add(v2);
}
map3.put(e.getKey(), list);
}
for (Entry<String, String> e : map2.entrySet()) {
map3.put(e.getKey(), new ArrayList<String>(Arrays.asList(e.getValue())));
}
Java 8 introduces Map.merge(K, V, BiFunction), which makes this easy if not particularly concise:
Map<String, String> result = new HashMap<>(map1);
//or just merge into map1 if mutating it is okay
map2.forEach((k, v) -> result.merge(k, v, (a, b) ->
Integer.toString(Integer.parseInt(a) + Integer.parseInt(b))));
If you're doing this repeatedly, you're going to be parsing and creating a lot of strings. If you're generating the maps one at a time, you're best off maintaining a list of strings and only parsing and summing once.
Map<String, List<String>> deferredSum = new HashMap<>();
//for each map
mapN.forEach((k, v) ->
deferredSum.computeIfAbsent(k, x -> new ArrayList<String>()).add(v));
//when you're done
Map<String, String> result = new HashMap<>();
deferredSum.forEach((k, v) -> result.put(k,
Long.toString(v.stream().mapToInt(Integer::parseInt).sum())));
If this summing is a common operation, consider whether using Integer as your value type makes more sense; you can use Integer::sum as the merge function in that case, and maintaining lists of deferred sums would no longer be necessary.
Try this
Map<String,String> map1= new HashMap<String, String>(){{
put("no1","123"); put("no2","5434"); put("no5","234");}};
Map<String,String> map2 = new HashMap<String, String>(){{
put("no1","523"); put("no2","234"); put("no3","234");}};
Map<String,String> newMap=map1;
for(String a:map2.keySet()){
if(newMap.keySet().contains(a)){
newMap.put(a,""+(Integer.parseInt(newMap.get(a))+Integer.parseInt(map2.get(a))));
}
else{
newMap.put(a,map2.get(a));
}
}
for(String k : newMap.keySet()){
System.out.println("key : "+ k + " value : " + newMap.get(k));
}

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