I am attempting to sort a hashmap on type <Integer,Double> using a TreeMap and a SortedMap I want to sort on the absolute values of the Doubles but I also want to retain the sign value (hence not storing as an unsigned Double).
Below is the code I am using, however I am not getting the values I expect, presumably due to the use of hashcode() can anybody point out how to fix this?
Map<Integer,Double> termWeights = new HashMap<Integer,Double>();
SortedMap sortedData = new TreeMap(new ValueComparer(termWeights));
System.out.println(termWeights);
sortedData.putAll(termWeights);
System.out.println(sortedData);
class ValueComparer implements Comparator {
private Map _data = null;
public ValueComparer(Map data) {
super();
_data = data;
}
public int compare(Object o1, Object o2) {
Double e1 = Math.abs((Double) _data.get(o1));
Double e2 = Math.abs((Double) _data.get(o2));
int compare = e2.compareTo(e1);
if (compare == 0) {
Integer a = o1.hashCode();
Integer b = o2.hashCode();
return b.compareTo(a);
}
return compare;
}
}
Thanks
Can you give an example of expected and actual results?
Sorted map: {17=1.644955871228835, 0=-1.029545248153297, 10=-5.291765636407169E-4, 9=-3.331976978545177E-4, 1=-2.7105555587851366E-4, 2=-2.7105555587851366E-4, 7=-2.0897436261984377E-4, 8=-1.305197184270594E-5, 3=0.0, 4=0.0, 5=0.0, 6=0.0, 11=0.0, 12=0.0, 13=0.0, 14=0.0, 15=0.0, 16=0.0, 18=0.0, 19=0.0, 20=0.0, 21=0.0, 22=0.0}
So what is the problem?
That looks correctly sorted from biggest to smallest.
But I would avoid using hashCode in the tie-break secondary comparator, because you need it to never return the same value for different inputs. In this case, it works, because you are calling it on an Integer, where hashCode just returns the same int. But if you used Long or String keys in your map, it would have collisions. Compare the two keys directly instead.
And finally, you must not change the weights after starting to use the comparator. That will lead to an inconsistent TreeMap.
Related
I am having a hard time understanding the right syntax to sort Maps which values aren't simply one type, but can be nested again.
I'll try to come up with a fitting example here:
Let's make a random class for that first:
class NestedFoo{
int valA;
int valB;
String textA;
public NestedFoo(int a, int b, String t){
this.valA = a;
this.valB = b;
this.textA = t;
}
}
Alright, that is our class.
Here comes the list:
HashMap<Integer, ArrayList<NestedFoo>> sortmePlz = new HashMap<>();
Let's create 3 entries to start with, that should show sorting works already.
ArrayList<NestedFoo> l1 = new ArrayList<>();
n1 = new NestedFoo(3,2,"a");
n2 = new NestedFoo(2,2,"a");
n3 = new NestedFoo(1,4,"c");
l1.add(n1);
l1.add(n2);
l1.add(n3);
ArrayList<NestedFoo> l2 = new ArrayList<>();
n1 = new NestedFoo(3,2,"a");
n2 = new NestedFoo(2,2,"a");
n3 = new NestedFoo(2,2,"b");
n4 = new NestedFoo(1,4,"c");
l2.add(n1);
l2.add(n2);
l2.add(n3);
l2.add(n4);
ArrayList<NestedFoo> l3 = new ArrayList<>();
n1 = new NestedFoo(3,2,"a");
n2 = new NestedFoo(2,3,"b");
n3 = new NestedFoo(2,2,"b");
n4 = new NestedFoo(5,4,"c");
l3.add(n1);
l3.add(n2);
l3.add(n3);
l3.add(n4);
Sweet, now put them in our Map.
sortmePlz.put(5,l1);
sortmePlz.put(2,l2);
sortmePlz.put(1,l3);
What I want now, is to sort the Entire Map first by its Keys, so the order should be l3 l2 l1.
Then, I want the lists inside each key to be sorted by the following Order:
intA,intB,text (all ascending)
I have no idea how to do this. Especially not since Java 8 with all those lambdas, I tried to read on the subject but feel overwhelmed by the code there.
Thanks in advance!
I hope the code has no syntatical errors, I made it up on the go
You can use TreeSet instead of regular HashMap and your values will be automatically sorted by key:
Map<Integer, ArrayList<NestedFoo>> sortmePlz = new TreeMap<>();
Second step I'm a little confused.
to be sorted by the following Order: intA,intB,text (all ascending)
I suppose you want to sort the list by comparing first the intA values, then if they are equal compare by intB and so on. If I understand you correctly you can use Comparator with comparing and thenComparing.
sortmePlz.values().forEach(list -> list
.sort(Comparator.comparing(NestedFoo::getValA)
.thenComparing(NestedFoo::getValB)
.thenComparing(NestedFoo::getTextA)));
I'm sure there are way of doing it with lambda but it is not actually required. See answer from Schidu Luca for a lambda like solution.
Keep reading if you want an 'old school solution'.
You cannot sort a map. It does not make sense because there is no notion of order in a map. Now, there are some map objects that store the key in a sorted way (like the TreeMap).
You can order a list. In your case, makes the class NestedFoo comparable (https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html). Then you can invoke the method Collections.sort (https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#sort-java.util.List-) on your lists.
Use TreeMap instead of HashMap, it solves the 1st problem: ordering entries by key.
After getting the needed list from the Map, you can sort the ArrayList by valA, valB, text:
l1.sort(
Comparator.comparing(NestedFoo::getValA).thenComparing(NestedFoo::getValB).thenComparing(NestedFoo::getTextA)
);
And change your NestedFoo class definition like this:
class NestedFoo {
int valA;
int valB;
String textA;
public NestedFoo(int a, int b, String t) {
this.valA = a;
this.valB = b;
this.textA = t;
}
public int getValA() {
return valA;
}
public void setValA(int valA) {
this.valA = valA;
}
public int getValB() {
return valB;
}
public void setValB(int valB) {
this.valB = valB;
}
public String getTextA() {
return textA;
}
public void setTextA(String textA) {
this.textA = textA;
}
}
When using treemap for sorting keep in mind that treemap uses compareTo instead of equals for sorting and to find duplicity. compareTo should be incosistent with equals and hashcode when implemented for any object which will be used as key. You can look for a detailed example on this link https://codingninjaonline.com/2017/09/29/unexpected-results-for-treemap-with-inconsistent-compareto-and-equals/
Hi I'm trying to sort an object based on a value of that object. Originally I used TreeMap which did the sorting but there were some non-unique keys which were removed so that didn't work. I googled around and came across Guava MultiMap. But how do I actually use this to sort the values?
Basically I'm trying to sort budget information based on the diffYTD_percentage value. Thanks!
Multimap<Double, BudgetInformation> multiMap = ArrayListMultimap.create();
for (Budget budget : budgets) {
BudgetInformation budgetInfo = getBudget(budget.getId());
double actualToDate = budgetInfo.getActualToDate();
double budgetToDate = budgetInfo.getTotalBudgetToDate();
double diffYTD_value = budgetToDate - actualToDate;
double diffYTD_percentage_value = 0.0;
if (budgetToDate != 0.0) {
double fraction = actualToDate / budgetToDate;
fraction = fraction - 1;
diffYTD_percentage_value = fraction * 100;
}
multiMap.put(diffYTD_percentage_value, budgetInfo);
}
Iterator<BudgetInformation> budgetIterator = multiMap.values().iterator();
Using Tree in order to sort collection is wrong approach. In Java there are dedicated utility methods to sort list, Collections.sort(List<T extends Comparable<? super T>> list) and Collections.sort(List<T> list, Comparator<? super T> c). The first is used to sort list where elements have natural ordering (basically implement Comparable interface), the later is used in cases like your own, when you need to sort elements using custom ordering.
So, basically what you need to do is to create Comparator that will compare two BusinessInfo instances based on diffYTD_percentage_value and call Collections.sort with this comparator.
Comparator<BudgetInformation> budgetInfoCmp = new Comparator<BudgetInformation>() {
private double getDiffYTDPercentage(BudgetInformation budgetInfo) {
double actualToDate = budgetInfo.getActualToDate();
double budgetToDate = budgetInfo.getTotalBudgetToDate();
double diffYTDValue = budgetToDate - actualToDate;
double diffYTDPercentageValue = 0.0;
if (budgetToDate != 0.0) {
double fraction = actualToDate / budgetToDate;
fraction = fraction - 1;
diffYTDPercentageValue = fraction * 100;
}
return diffYTDPercentageValue;
}
#Override
public int compare(BudgetInformation o1, BudgetInformation o2) {
return Double.compare(getDiffYTDPercentage(o1), getDiffYTDPercentage(o2));
}
};
List<BudgetInformation> budgetInformationsToSort = getBudgetInformations();
Collections.sort(budgetInformationsToSort, budgetInfoCmp);
Also try to avoid using underscore in variable naming, as under Java naming convention variable names should be in camel case.
How about using TreeMultiMap? It doesnt support duplicate key-value pair. But duplicate keys are fine.
Somebody please tell me the function containsKey() of HashMap that how does it work internally. does it use equals or hashcode function to match the key. I am using string keys for a hashmap and when I am using the key dynamically the containskey returns false. e.g. (Just a sample code not the original one I am using in application)
class employee {
employee(String name) {
return name;
}
}
class test {
HashMap hm = new HashMap();
hm.put("key1",new Employee("emp1"));
hm.put("key2",new Employee("emp2"));
hm.put("key3","emp4");
hm.put("new Employee("emp5")","emp4");
System.out.println(hm.containsKey("emp5"));
}
The key is an Employee object, not a string, in containsKey you have a string. That comparison will return false, because string "emp5" is not equal to an object Employee.
Here is a quote from containsKey doc:
Returns true if this map contains a mapping for the specified key. More formally, returns true if and only if this map contains a mapping for a key k such that (key==null ? k==null : key.equals(k))
Since in your case key is a string, 'equals' will return 'true' only if k is a string as well and its content is the same as that of key.
Your code has many errors, this is invalid hm.put("new Employee("emp5")","emp4");
Also use generic types with collections
HashMap<String,employee> hm = new HashMap<String,employee>();
And name you class Employee not employee , Begin with capital for class names. Also you are calling new Employee Whereas you classname is employee.
According to the source for hashMap . It calls equals() on the keys (in your case which would mean equals for String) internally
public boolean containsKey(Object key)
{
int idx = hash(key);
HashEntry<K, V> e = buckets[idx];
while (e != null)
{
if (equals(key, e.key))
return true;
e = e.next;
}
return false;
}
Your valid code (assuming you are not trying to achieve something unusual) should look like this :-
class Employee {
String name;
Employee(String name) {
this.name = name;
}
}
class Test {
public void hello() {
HashMap<String,Employee> hm = new HashMap<String,Employee>();
hm.put("key1", new Employee("emp1"));
hm.put("key2", new Employee("emp2"));
hm.put("key3", new Employee("emp4"));
hm.put("key4", new Employee("emp5"));
System.out.println(hm.containsKey("key4"));
}
}
Corrected Code:
HashMap hm= new HashMap();
hm.put("key1",new Employee("emp1"));
hm.put("key2",new Employee("emp2"));
hm.put("key3","emp4");
System.out.println(hm.containsKey("key1"));
This will return true.
You are saving Employee object against String keys. So you need to check the valid key. In your case emp5 is not used as a key while adding elements to hashmap.
For your second question:
It internally checks hashcode of the key first. If hashcodes are same it will check equals method.
Assuming
employee(String name) {
return name;
}
Is not a constructor and it is some method this piece of code will not compile. As you are returning String but you dint specify the return type in the method.
Moreover this line hm.put("new Employee("emp5")","emp4");
you have specified the key as
new Employee("emp5") and you are searching using the key emp5 in the containsKey() obviously it will return false because
containsKey() -Returns true if this map contains a mapping for the specified key.
Internally, a hash map can be implemented with an array of linked lists.
The key is passed to a routine (the hash) which gives back a number. The number is then divided by the size of the array, giving a remainder. That remainder is the linked list you then travel to see if any of the nodes exactly matches the key.
The advantages are that if you have a properly balanced hash function, and (let's say) an array of 32 items, you can quickly discard the searching of 31/32 (or +90%) of your possible values in a constant time operation.
Other means of implementation exist; however, they are computationally similar.
An example of a (very bad) hash algorithm for Strings might be to simply add up all the ASCII character values. Very good hash algorithms tend to give back an evenly distributed number based on the expected inputs, where incremental inputs do not incrementally fill adjacent buckets.
So, to find out if a hash map contains a key, get the result of the hash function on the key, and then walk down the correct linked list checking each entry for the key's presence.
In C, a "node" in the linked list.
struct Node {
char* key;
char* value;
struct Node* next;
};
In C, the "hashmap"
struct HashMap {
int size;
struct Node* listRoots;
};
The algorithm
int containsKey(HashMap* hashMap, char* key) {
int hash = hashFunc(key);
Node* head = hashMap->listRoots[hash % hashMap->size];
while (head != 0) {
if (strcmp(head->key, key)) {
return TRUE;
}
}
return FALSE;
}
Keep in mind my C is a bit rusty, but hopefully, you'll get the idea.
I know that TreeSet stores objects in a sorted manner. But is there a way that i can customize the order?
For example if i have a treeSet:
TreeSet t1 = new TreeSet();
t1.add("c");
t1.add("d");
t1.add("a");
And now if i iterate over it>
Iterator it1 =t1.iterator();
while(it1.hasNext()){
Object o1 = it1.next();
System.out.println(o1);
}
i will always get the order as: a>c>d, however i want it to return the order the same as i added the elements in it i.e c>d>a?
Use LinkedHashSet for it,
TreeSet sorts the element, and for string it sorts based on natural order( this is how its comparator is implemented), If you want to manage the insertion order then you need to user LinkedHashSet
and if you don't need the uniquness (feature of set) then go for List
Since you mention about being bound to use TreeSet, something like this comes to my mind:
Set<String> result = new TreeSet<String>(new Comparator<String>(){
#Override
public int compare(String arg0, String arg1) {
return returnCode(arg0).compareTo(returnCode(arg1));
}
});
where:
private Integer returnCode(String p){
int code = 0;
String id = p.toLowerCase();
if ("a".equalsIgnoreCase(id)) code = 3;
else if ("b".equalsIgnoreCase(id)) code = 2;
else if ("c".equalsIgnoreCase(id)) code = 1;
//etc
return new Integer(code);
}
So basically you are implementing your own comparator which is nothing but assigning certain integer values to the inserted String (which i assume you know already).
NOTE: this solution will not work, incase you do not catch the option in your returnCode() method. I assume you already know the data that is being fed to the TreeSet.
It is much more easy:
TreeSet treeSetObj = new TreeSet(Collections.reverseOrder());
I have got a good answer. It's my first one.
import java.util.*;
class M
{
public static void main(String args[])
{
TreeSet<String> t=new TreeSet<>(new MyComparator());
t.add("c");
t.add("d");
t.add("a");
System.out.println(t);//[c,d,a] not [a,c,d] ....your answer
}
}
class MyComparator implements Comparator
{
public int compare(Object o1,Object o2)
{
String i1=(String)o1;
String i2=(String)o2;
return +1; //Store elements as they come
}
}
What basically +1 does store the elements in the order in which they come.
Always remember
if I write return +1 it means to store the elements in the order in which they come.
if I write return -1 it means to store the elements in reverse order in which they come.
I need a sorted set of objects and am currently using the TreeSet. My problem is that the compareTo of the objects will often return 0, meaning the order of those two objects is to be left unchanged. TreeMap (used by TreeSet by default) will then regard them as the same object, which is not true.
What alternative to TreeMap can I use?
Use case: I have a set of displayable objects. I want to sort them by Y coordinate, so that they are rendered in the correct order. Of course, two objects may well have the same Y coordinate.
You're defining one criteria to compare, but you need to add extra criteria.
You say:
I have a set of displayable objects. I want to sort them by Y coordinate, so that they are rendered in the correct order. Of course, two objects may well have the same Y coordinate.
So, If two elements have the same Y coordinate, what you you put first? What would be the other criteria?
It may be the creation time, it may be the x coordinate, you just have to define it:
Map<String,Thing> map = new TreeMap<String,Thing>(new Comparator<Thing>(){
public int compare( Thing one, Thing two ) {
int result = one.y - two.y;
if( result == 0 ) { // same y coordinate use another criteria
result = one.x - two.x;
if( result == 0 ) { //still the same? Try another criteria ( maybe creation time
return one.creationTime - two.creationTime
}
}
return result;
}
});
You have to define when one Thing is higher / lower / equal / than other Thing . If one of the attributes is the same as other, probably you should not move them. If is there other attribute to compare the use it.
The issue you're running into is that compareTo returning 0 means that the objects are equal. At the same time, you're putting them into a set, which does not allow multiple copies of equal elements.
Either re-write your compareTo so that unequal elements return different values, or use something like a java.util.PriorityQueue which allows multiple copies of equal elements.
I've done this before. It's an ordered multi-map and it is just a TreeMap of List objects. Like this..
Map<KeyType, List<ValueType>> mmap = new TreeMap<KeyType, List<ValueType>>();
You need to construct a new LinkedList every time a new key is introduced, so it might be helpful to wrap it in a custom container class. I'll try to find something.
So, I threw this custom container together quickly (completely untested), but it might be what you are looking for. Keep in mind that you should only use this type of container if you are truly looking for an ordered map of value lists. If there is some natural order to your values, you should use a TreeSet as others have suggested.
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class MTreeMap<K, V> {
private final Map<K, List<V>> mmap = new TreeMap<K, List<V>>();
private int size = 0;
public MTreeMap() {
}
public void clear() {
mmap.clear();
size=0;
}
public boolean containsKey(K key) {
return mmap.containsKey(key);
}
public List<V> get(K key) {
return mmap.get(key);
}
public boolean isEmpty() {
return mmap.isEmpty();
}
public Set<K> keySet() {
return mmap.keySet();
}
public Collection<List<V>> valueLists() {
return mmap.values();
}
public void put(K key, V value) {
List<V> vlist = mmap.get(key);
if (null==vlist) {
vlist = new LinkedList<V>();
mmap.put(key, vlist);
}
vlist.add(value);
++size;
}
public List<V> remove(Object key) {
List<V> vlist = mmap.remove(key);
if (null!=vlist) {
size = size - vlist.size() ;
}
return vlist;
}
public int size() {
return size;
}
public String toString() {
return mmap.toString();
}
}
Here's a rudimentary test:
public class TestAnything {
public static void main(String[] args) {
MTreeMap<Integer, String> mmap = new MTreeMap<Integer, String>();
mmap.put(1, "Value1");
mmap.put(2, "Value2");
mmap.put(3, "Value3");
mmap.put(1, "Value4");
mmap.put(3, "Value5");
mmap.put(2, "Value6");
mmap.put(2, "Value7");
System.out.println("size (1) = " + mmap.get(1).size());
System.out.println("size (2) = " + mmap.get(2).size());
System.out.println("size (3) = " + mmap.get(3).size());
System.out.println("Total size = " + mmap.size());
System.out.println(mmap);
}
}
The output is this:
size (1) = 2
size (2) = 3
size (3) = 2
Total size = 7
{1=[Value1, Value4], 2=[Value2, Value6, Value7], 3=[Value3, Value5]}
I have one idea of my own, but it's more of a workaround
int compare(Object a, Object b) {
an = a.seq + (a.sortkey << 16); // allowing for 65k items in the set
bn = b.seq + (a.sortKey << 16);
return an - bn; // can never remember whether it's supposed to be this or b - a.
}
sortKey = what really matters for the sorting, for example an Y coordinate
seq = a sequence number assigned to objects when added to the set
There are 2 important things to remember when using sorted sets (e.g. TreeSet) :
1) They are sets; two equal elements are not allowed in the same collection
2) Equality must be consistent with the comparison mechanism (either comparator or comparable)
Therefore, in your case you should "break ties" by adding some secondary ordering criteria. For example: first use Y axis, then X, and then some unique object identifier.
See also http://eyalsch.wordpress.com/2009/11/23/comparators/