Since this is the requirement of putting custom class object keys in the TreeMap in the first place, you do not need to do anything extra for the containsKey method to work as expected. Let’s have a look at an example of that.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

importjava.util.TreeMap;

classEmpimplementsComparable<Emp>{

privateIntegerid;

privateStringname;

publicEmp(Integerid,Stringname){

this.id=id;

this.name=name;

}

publicStringtoString(){

return"["+this.id+" => "+this.name+"]";

}

publicintgetId(){

returnthis.id;

}

/*

* This method will compare this employee object with another

*/

publicintcompareTo(Empo){

returnthis.getId()-o.getId();

}

}

publicclassTreeMapCheckIfKeyExistsExample{

publicstaticvoidmain(String[]args){

TreeMap<Emp,Integer>treemap=newTreeMap<Emp,Integer>();

treemap.put(newEmp(3,"Jack"),3);

treemap.put(newEmp(1,"Emily"),1);

treemap.put(newEmp(2,"Maria"),2);

//this will return true

System.out.println(treemap.containsKey(newEmp(1,"Emily")));

//this will return false

System.out.println(treemap.containsKey(newEmp(4,"John")));

}

}

Output

1

2

true

false

As you can see from the output since our Emp class has already implemented the Comparable interface, the containsKey method worked as expected.

About the author

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.