I am trying to create a HashMap using strings as keys and tree sets sorted using a custom comparator (CandidateComparator) as values.
HashMap<String, TreeSet<Candidate>> map = new HashMap<String, TreeSet<Candidate>(new CandidateComparator())>();
I can't see what I've done wrong. I was using this site:
http://www.java2novice.com/java-collections-and-util/treeset/sort-by-objects/
as a reference.
This statement yields two syntax errors:
1. Insert '>' to complete ReferenceType1;
2. Expression expected after this token '(' - refers to the last '(' of the statement.
What am I doing wrong?
The Comparator refers to the TreeSet, not the HashMap. Moreover, the Comparator is not part of the TreeSet's type definition (as is, for example TreeSet<Candidate>) - it's only passed when a new instance is created.
So, to make a long story short - drop it from the definition and pass it when you construct an object:
Map<String, TreeSet<Candidate>> map = new HashMap<String, TreeSet<Candidate>>();
map.put ("SomeString", new TreeSet<Candidate>(new CandidateComparator()));
The HashMap should be initialized this way:
HashMap<String, TreeSet<Candidate>> map = new HashMap<String, TreeSet<Candidate>>();
No Comparator is required for the HashMap itself. You'll need instances of TreeSet to populate the HashMap, and each of them would require a Comparator.
Comparator<Candidate> cmp = new CandidateComparator();
TreeSet<Candidate> ts1 = new TreeSet<Candidate>(cmp);
... populate ts1 ...
map.put ("someKey1", ts1);
TreeSet<Candidate> ts2 = new TreeSet<Candidate>(cmp);
... populate ts2 ...
map.put ("someKey2", ts2);
Related
Have a
List<Map<String, Object>> allPoints = new LinkedList<>();
Each map contains a "name" key with a String value;
Need to create a
List<Map<String, Object>> expectedPoints
There are duplicate names in the list; for these, want to keep the last one only.
E.g. if the list has three items, and first and third items both have"name" with value "abc", the resulting list should only contain the second and third items from the original list.
One way to do it is by using an auxiliary map:
Map<String, Map<String, Object>> map = new LinkedHashMap<>(allPoints.size(), 0.75f, true);
allPoints.forEach(point -> map.put((String)point.get("name"), point));
List<Map<String, Object>> expectedPoints = new ArrayList<>(map.values());
This works because Map.put either puts a new entry to the map or overwrites the value of an existing entry with the new one, thus keeping only the last point associated with the name.
I'm creating an access-ordered LinkedHashMap by using its overloaded constructor. This is to maintain the same order as in the allPoints list.
In case you have the constraint on one or more key-value pairs and flexible to use a Set, write your own Comparator and use descendingIterator on LinkedList and write to TreeSet. See code below:
LinkedList<Map<String, Object>> allPoints = new LinkedList<>();
Set<Map<String, Object>> expectedPoints = new TreeSet<>((objectMap1, objectMap2) ->
objectMap2.get("name").equals(objectMap1.get("name")) ? 0 : -1
);
allPoints.descendingIterator().forEachRemaining(expectedPoints::add);
I have to maintain the list of indexes for each of the key value in HashMap.
So i declared HashMap as
HashMap<Integer,HashSet<Integer> hset = new HashSet<Integer>()> hm = new HashMap<Integer,HashSet<Integer> hset = new HashSet<Integer>()>();
but the above declaration seems to be not correct.
So i declared it as
HashSet<Integer> hset = new HashSet<Integer>();
but here the problem is,how could i declare the type of objects stored in HashSet i,e Integer, bacause in the above declaration the HashSet is rawtype.
I would like to add more here,
You need to initialize your outer Map like below
HashMap<Integer,HashSet<Integer>> map = new HashMap<Integer,HashSet<Integer>>();
and inner collection like this
HashSet<Integer> hset = new HashSet<Integer>();
And you insert the values like below in map and your hash set.
hset.add(1);
hset.add(2);
map.put(100,hset);
hset = new HashSet<Integer>();
hset.add(3);
hset.add(4);
map.put(101,hset);
So every time you need new instance of HashSet to put in map.
You can get inner HashSet by using Map key you used to insert.
HashSet<Integer> hset=map.get(100); //Same map
Here is your declaration should look like
HashMap<Integer,HashSet<Integer>> map = new HashMap<Integer>,HashSet<Integer>>
Second declaration you have provided for Hashset is correct. Its not raw type. Did you try adding a any other type of element to it ?
Try this it will work :
Map<Integer, Set<Integer>> map = new HashMap<Integer, Set<Integer>>();
you can easily Set Using Map tag only .
or
Create the Object Of Hashmap and put the value from Refrence. it will work
static Map<Integer,HashMap<String,HashMap<String,String>>> maps = new HashMap<Integer, HashMap<String,HashMap<String,String>>>();
I want to insert the elements inside the HashMap I declared above , the inner most hashmap has values ready which I can use , now I am using it like ,
static Map<String,String> values = new HashMap<String, String>();
maps.put(1, new HashMap<<new String("")>, values>());
How can I achieve this ?
static Map<String,String> values1 = new HashMap<String,String>();
static Map<String,Map<String,String>> values2 = new HashMap<String,Map<String,String>>();
values2.put("", values1);
maps.put(1,values2);
btw, if you have java 7, you can use:
Map<String,String> values1 = new HashMap<>();
and so on for others
In cases you have map inside a map (inside a map), consider using Apache MultiKeyMap.
Coding will be more intuitive
It will improve the readability of your code
It will prevent many if(map.get(key) != null) blocks you will probably have in your code.
Why not to have instance of HashMap. When you wan to insert new value, you need to have Integer, String, String key and String value.
You continuously select nested HashMaps according to keys and then insert value to the most inner HashMap.
map.get(key1).get(key2).insert(key3, value)
I have a problem in JAVA when i'm trying to return a HashMap that I have added to a list of type: List<Object>. I know I can use other type of lists, but I need to use List<Object>
List<Object> listOfObjects = new ArrayList<Object>();
HashMap<String, String> hashmap = new HashMap<String,String>();
hashmap.put("x", "foo");
hashmap.put("y", "bar");
listOfObjects.add(hashmap);
for (int i = 0; i < listOfObjects.size(); i++) {
System.out.println(listOfObjects.get(i));
}
I have added my hashmap to my listOfObject, but how do I get the HashMap from the listOfObject such that I can use the HashMap-commands. fx: hashmap.get("x) and it will return "foo".
Normally i thought i could just write: listOfObjects.get(0).get("x") and it would return "foo" but that does not work.
If anyone know another work around that's find but I just need to use a List.
Normally i thought i could just write: listOfObjects.get(0).get("x") and it would return "foo" but that does not work.
No, it wouldn't - because the type of listOfObjects.get(0) is just Object. How do you expect the compiler to know that it's meant to be a map?
You can use:
HashMap<String, String> map = (HashMap<String, String>) listOfObjects.get(0);
// Use map...
... but be aware that due to the nature of generics in Java, that cast isn't really ensuring that all the key/value pairs in the map are "string to string". The cast would work even if you'd originally used:
Map<Integer, Integer> badMap = new HashMap<Integer, Integer>();
badMap.put(0, 10);
listOfObjects.add(badMap);
You'll get a warning for this, but it's important to understand what it means. It's not clear what your use case is, but if you can make it more strongly typed (perhaps create a new class which contains a Map<String, String>?) that would be good. Is every element of your list going to be a map? If so, why are you using List<Object> rather than a more strongly-typed list? If some elements aren't going to be maps, how can you tell which ones will be? (These are the sort of things you should be thinking about carefully.)
I hope this will help u..
List<Object> listOfObjects = new ArrayList<Object>();
HashMap<String, String> hashmap = new HashMap<String,String>();
hashmap.put("x", "foo");
hashmap.put("y", "bar");
listOfObjects.add(hashmap);
for (int i = 0; i < listOfObjects.size(); i++) {
System.out.println(((HashMap<String, String>)listOfObjects.get(i)).get("x"));
}
Normally as your list is of type of object . so first cast it to HashMap type and then get the value from map
please notice the following code
System.out.println(((HashMap<String, String>)listOfObjects.get(i)).get("x"));
Is there a method in java.util.Map or any util to perform an intersection on two maps? (To intersect two maps by the "keys")
I am not able to find any. I can always implement my own intersection logic, but I was hoping there is already some operation in one of the java.util.* classes that would do this.
How about:
Map map1 = ...;
Map map2 = ...;
Map result = new ...(map1);
result.keySet().retainAll(map2.keySet());
or:
Map map1 = ...;
Map map2 = ...;
Set result = new ...(map1.keySet());
result.retainAll(map2.keySet());
If you're using Guava, you can use Maps.difference to get a MapDifference object, from which you can extract the entriesInCommon() and entriesDiffering() as maps. (Disclosure: I contribute to Guava.)
Guava's Sets.intersection(Set, Set) should do the job, with the keySet of each Map passed in as parameters.
I would recommend apache collectionUtils#intersection
Do the following:
Collection intersection=
CollectionUtils.intersection(map1.keySet(),map2.keySet());
To test for intersection you can use the containsAll() operation. Which 'Returns true if this set contains all of the elements of the specified collection. If the specified collection is also a set, this method returns true if it is a subset of this set.'
To get a collection of these intersecting elements you can use the retainAll() operation instead.
These methods are both found here
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Set.html
Loop over one map's keys, see if they're in the second map:
private Map getIntersection(Map mapOne, Map mapTwo)
{
Map intersection = new HashMap();
for (Object key: mapOne.keySet())
{
if (mapTwo.containsKey(key))
intersection.put(key, mapOne.get(key));
}
return intersection;
}