I'm having some problems with TreeMap constructors. I have a class with 2 TreeMap<String, Client> inside it. A tree sorted by name and another sorted by number.(Client class : String name, int number, ...)
private TreeMap<String, Client> nameTree;
private TreeMap<Integer, Client> numberTree;
How do I build the constructors for this class? So far I wrote this:
public ManagerTreeMap(){
nameTree = new TreeMap<String, Client>(new StringComparator());
numberTree = new TreeMap<Integer, Client>(new IntegerComparator());
}
My major problem is the construtor "TreeMap(Comparator c)". Can i write two comparators? if not what do I have to do?
public ManagerTreeMap(Comparator<String> cp){
nameTree = new TreeMap<String, Client>(cp);
}
public ManagerTreeMap(Comparator<Integer> cpt){
nameTree = new TreeMap<Integer, Client>(cpt);
}
It seems that you don't need custom comparators.
public ManagerTreeMap(){
nameTree = new TreeMap<String, Client>();
numberTree = new TreeMap<Integer, Client>();
}
Maybe
public ManagerTreeMap(Comparator<String> cs, Comparator<Integer> ci){
nameTree = new TreeMap<String, Client>(cs);
numberTree = new TreeMap<Integer, Client>(ci);
}
Related
This is my code. My intention is create a hashmap with 4 values, then export this class as a jar, add it to another project, and use the hashmap values there.
I'm getting error in all the "hmap.put". I'm unable to understand what I'm doing wrong. Please help.
import java.util.HashMap;
public class MyFirstClass {
private HashMap<Integer, String> hmap = new HashMap<Integer, String>();
hmap.put(2, "Jane");
hmap.put(4, "John");
hmap.put(3, "Klay");
hmap.put(1, "Deena");
public HashMap<Integer, String> gethmap()
{
return this.hmap;
}
public void sethmap(HashMap hmap)
{
this.hmap = hmap;
}
}
import java.util.HashMap;
public class MyFirstClass {
private HashMap<Integer, String> hmap = new HashMap<Integer, String>() {
{
hmap.put(4, "John");
hmap.put(3, "Klay");
hmap.put(1, "Deena");
}
};
public HashMap<Integer, String> gethmap() {
return this.hmap;
}
public void sethmap(HashMap<Integer, String> hmap) {
this.hmap = hmap;
}
}
Above code will help you to get the result which you desire. You should also note that you can not use instance variable directly inside class. you have to use that inside method only.
Java doesn't allow executing any statements outside of the scope of any method, field initialization or static block - that's why you get an error.
I suppose, your intent is to do some initialization with that four lines. And Java has support for such kind of initialization - it is the class constructor. So the proper code would look like the following:
import java.util.HashMap;
public class MyFirstClass {
private HashMap<Integer, String> hmap = new HashMap<Integer, String>();
// this is a constructor
public MyFirstClass() {
hmap.put(2, "Jane");
hmap.put(4, "John");
hmap.put(3, "Klay");
hmap.put(1, "Deena");
}
// here goes your other code
}
This way every object of MyFirstClass you create using new MyFirstClass() will contain the data you put in the constructor.
You can read more about the constructors in Java in the official documentation: https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
There are multiple ways to do this. Easiest one is to just add brackets to your put statements:
import java.util.HashMap;
public class MyFirstClass {
private HashMap<Integer, String> hmap = new HashMap<Integer, String>();
{
hmap.put(2, "Jane");
hmap.put(4, "John");
hmap.put(3, "Klay");
hmap.put(1, "Deena");
}
public HashMap<Integer, String> gethmap() {
return this.hmap;
}
public void sethmap(HashMap hmap) {
this.hmap = hmap;
}
}
You should add a constructor to your class:
public MyFirstClass() {
this.hmap = new HashMap<Integer,String>();
// you can do .put here if you wish
}
And change the hmap field to:
private HashMap<Integer, String> hmap;
You're using a method outside of a method. You cannot call Hashmap.put within the class but outside the method - as was mentioned you want to do that in the constructor of the class
public class MyFirstClass {
public MyFirstClass() { //put it here }
}
You can put it in a static block, just as:
private static final Map<Integer, String> NAME_MAP = new HashMap<Integer, String>() {
private static final long serialVersionUID = 1L;
{
NAME_MAP.put(2, "Jane");
NAME_MAP.put(4, "John");
NAME_MAP.put(3, "Klay");
NAME_MAP.put(1, "Deena");
}
};
I have a map defined like this:
Map<Long, Long> foo = new TreeMap<Long, Long>();
For each entry into the map, I also want to map those entries to a Boolean. How can I do this? This is what I tried so far but it doesn't look right. What I want to achieve is that for every entry in mask, there should be a corresponding Boolean value that it is assigned to.
Map<Long, Boolean> mask = new HashMap<Long, Boolean>();
SortedMap<Long, Map<Long, Boolean>> pairs = new TreeMap<Long, Map<Long, Boolean>>();
mask.put(new Long(2), Boolean.FALSE);
mask.put(new Long(3), Boolean.FALSE);
mask.put(new Long(3), Boolean.FALSE);
pairs.put(new Long(1), new Long(2));
pairs.put(new Long(1), new Long(3));
pairs.put(new Long(2), new Long(3));
The constraint is that I can only use the built-in types. I had a solution before which had a custom object which allowed me to easily achieve this but due to the project design, I cannot create new types.
Create a class that encapsulates both values and make a map of that:
class Pair {
public final boolean booleanValue;
public final long longValue;
public Pair(boolean booleanValue, long longValue) {
this.booleanValue = booleanValue;
this.longValue = longValue;
}
}
Map<Long,Pair> map = new HashMap<>();
map.put(1L, new Pair(false, 123));
map.put(2L, new Pair(true, 456));
map.put(3L, new Pair(false, 789));
Or use two maps having the same keys:
Map<Long,Boolean> map1 = new HashMap<>();
Map<Long,Long> map2 = new HashMap<>();
map1.put(1L, false); map2.put(1L, 123L);
map1.put(2L, true); map2.put(2L, 456L);
map1.put(3L, false); map2.put(3L, 789L);
If I understand you, you want to map both a Long and a Boolean to the same key entry?
If that's the case, and you can't create your own custom objects, you just need to have two maps:
Map<Long, Long> pairs = new HashMap<Long, Long>();
Map<Long, Boolean> mask = new HashMap<Long, Boolean>();
Then just use the same key entry for both:
pairs.put(1L, 5L);
mask.put(1L, false);
pairs.put(2L, 20L);
mask.put(2L, true);
and so on.
Create a new object that has a Long and Boolean and that object put into the map.
What about a holder ?
private class MyHolder
{
public Boolean boolValue;
public Long longValue;
}
Map<Long, MyHolder> myMap = new HashMap<Long, MyHolder>();
MyHolder h = new MyHolder();
h.boolValue = true;
h.longValue = 1L;
myMap.put(1L, h);
I am trying to create a TreeMap with a generic type but I am unable to. I am doing this because my map can like these:
Map<String, QueryTerm> terms = new TreeMap<String, QueryTerm>();
Map<String, String> params = new TreeMap<String, String>();
So instead of creating multiple functions to handle the maps with different types I want to create one which both types.
How can I do this and what am I doing wrong?
Function:
private Map<String, ? extends Object> setDatumMap(UserSession session, String parameterName)
{
Map<String, ? extends Object> map = new TreeMap<String, ? extends Object>();
//Get comma delimited list of filter keys. Split them and use them to retrieve associated values.
String sFilters = (String) session.getAttribute(parameterName);
String[] filterList = sFilters.split(",");
for(String filterName : filterList)
{
String filterValue = (String) session.getAttribute(filterName);
if (filterValue != null && !filterValue.isEmpty())
{
filter.put(filterName, setQueryTermList(filterValue, ListType.BOOLEAN_LIST));
}
}
return filter;
}
You should simply instantiate the map like so:
Map<String, Object> map = new TreeMap<String, Object>();
You can't instantiate using a wildcard, and it's not necessary unless you expect that the compiler will cast to the appropriate class by guessing what value you are going to get. We didn't get there yet.
you need to change you this line :
private Map<String, ? extends Object> setDatumMap(UserSession session, String parameterName)
{
Map<String, ? extends Object> map = new TreeMap<String, ? extends Object>();
//rest of your code
To
private Map<String, Object> setDatumMap(UserSession session, String parameterName)
{
Map<String, Object> map = new TreeMap<String, Object>();
//rest of your code.
This will work.
I have a list of maps
List<Map<String, Object>> people = new ArrayList<Map<String,Object>>();
that gets populated like so
map.put("firstName",John);
map.put("lastName",Smith);
map.put("type","1"); //type is either 1 or a 0
people.add(map);
and what I want to do with this list after it gets populated is so have all the people as type 0 at the top of the list and all with type 1 at the bottom.
I know I need to use a Comparator but I have never used one before so I dont know how to use one or how it works.
Could someone help me out
Like this
Collections.sort( people, new Comparator<Map<String, Object>>() {
#Override
public int compare( Map<String, Object> o1, Map<String, Object> o2 ) {
return (Integer.parseInt((String)o1.get( "type" ))) -
(Integer.parseInt((String)o2.get( "type" )));
}
} );
However, there are many ways to make this better. If you cannot use a Person object to represent the map as suggested by #Pshemo, then at least, use a reasonable data type for your type attribute. The best would be an enum:
public enum PersonType {
TYPE_1, TYPE_2
}
Then the comparisons are much cleaner and faster and much more readable.
Comparator is just an interface that needs to be implemented, it contains only one method that needs to be overriden.
For example:
List<Map<String, Object>> people = new ArrayList<Map<String,Object>>();
Map<String, Object> map = new HashMap<String, Object>();
map .put("firstName","John");
map.put("lastName","Smith");
map.put("type","1"); //type is either 1 or a 0
people.add(map);
Collections.sort(people, new Comparator<Map<String, Object>>() {
#Override
public int compare(Map<String, Object> o1, Map<String, Object> o2) {
// you may compare your map here
return 0;
}
});
Try this
Collections.sort(people, new Comparator<Map<String, String>>() {
#Override
public int compare(Map<String, String> m1, Map<String, String> m2) {
return m1.get("type").compareTo(m2.get("type"));
}
});
You can try like this :
class ListByType
{
private static class MyComparator implements Comparator<HashMap<String,String>>
{
#Override
public int compare(HashMap mp1 , HashMap mp2)
{
return ((String)(mp1.get("type")).compareTo((String)mp2.get("type"));
}
}
public static void main(String[] args)
{
List<Map<String, String>> people = new ArrayList<Map<String,String>>();
HashMap<String,String> map = new HashMap<String,String>();
map.put("firstName","John");
map.put("lastName","Smith");
map.put("type","1"); //type is either 1 or a 0
people.add(map);
/*...
..
...
Add more maps here..
*/
//Sort the list
Collections.sort(people,new MyComparator());
}
}
I would like to know how can I iterate in a 2Dimensional HashMap? I am creating an Object TrueStringMap2D that does the following: It will be a map 2D, i mean 2 keys and one value.
But the iterator implemented here is not functional.. i didnt know how to redefine the Iterator method in TrueStringMap2D :S (if possible should be remove in the iterator() functional)
Anyone can help?
Thankyou very much!!
I'll reinterpret the question into something similar that I enjoy answering, and then hopefully the answer to that question is useful to you.
Here's the question I'll answer:
How do I write an iterator that iterates over all values in a Map<String, Map<String, String>>?
This is how I would solve it:
class TwoDimIterator implements Iterator<String> {
Iterator<Map<String, String>> outerIter;
Iterator<String> innerIter = Collections.<String>emptyList().iterator();
public TwoDimIterator(Map<String, Map<String, String>> twoDimMap) {
outerIter = twoDimMap.values().iterator();
advanceInner();
}
#Override
public boolean hasNext() {
return innerIter.hasNext();
}
#Override
public String next() {
String toReturn = innerIter.next();
advanceInner();
return toReturn;
}
private void advanceInner() {
while (!innerIter.hasNext()) {
if (!outerIter.hasNext()) {
innerIter = Collections.<String>emptyList().iterator();
return;
}
innerIter = outerIter.next().values().iterator();
}
}
#Override
public void remove() {
throw new UnsupportedOperationException();
}
}
Test code:
class Test {
public static void main(String[] args) {
// Create a map
Map<String, Map<String, String>> twoDimMap =
new HashMap<String, Map<String, String>>();
// Fill it
Map<String, String> innerA = new HashMap<String, String>();
innerA.put("1", "A1");
innerA.put("2", "A2");
Map<String, String> innerB = new HashMap<String, String>();
innerB.put("1", "B1");
innerB.put("2", "B2");
twoDimMap.put("A", innerA);
twoDimMap.put("B", innerB);
// Create an iterator for the values:
Iterator<String> twoDimIter = new TwoDimIterator(twoDimMap);
while (twoDimIter.hasNext())
System.out.println(twoDimIter.next());
}
}
Output:
A2
A1
B2
B1