您的位置:首页 > 编程语言 > Java开发

Java Sorted Map Example

2015-06-07 21:14 351 查看
InthisexampleweshallshowyouhowtomakeuseofJavaSortedMap.A
SortedMap
isa
Map
thatsortitsentriesinascendingorderaccordingtothekeys’naturalordering,oraccordingtoa
Comparator
providedatthetimeofthe
SortedMap
creation.Allkeysinsertedintoa
SortedMap
mustimplementthe
Comparable
interface(orbeacceptedbythespecified
Comparator
).Furthermore,allsuchelementsmustbemutuallycomparable(i.e,MutuallyComparablesimplymeansthattwoobjectsaccepteachotherastheargumenttotheir
compareTo
method),Ifyoutrytosortkeyswhichdonotimplement
Comparable
ornothasaspecific
Comparator
,a
ClassCastException
willbethrown.

Tip1

java.lang.Comparable:intcompareTo(Objecto):


Thismethodcomparesthisobjectwithoobject.Returnedintvaluehasthefollowingmeanings.

positive
–thisobjectisgreaterthano

zero
–thisobjectequalstoo

negative
–thisobjectislessthano

Also,wecanuseourown
Comparator
.Ifyouneedtoknowmoreaboutthe
Comparable
and
Comparator
,TakealookonJavaComparableandComparatorExampletosortObjectsbyByronKiourtzoglou.

Tip2

All
SortedMap
implementationclassesshouldprovidefour“standard”constructorsasthefollowing:

Avoid(noarguments)constructor,whichcreatesanempty
SortedMap
sortedaccordingtothenaturalorderingofitskeys.

1
SortedMapsortedMap=
new
TreeMap();
Aconstructorwithasingleargumentoftype
Comparator
,whichcreatesanempty
SortedMap
sortedaccordingtothespecified
Comparator
.

1
Comparatorcomparator=
new
MyComparator();
2
SortedMapsortedMap=
new
TreeMap(comparator);
Aconstructorwithasingleargumentoftype
Map
,whichcreatesanew
Map
withthesamekey-valuemappingsasitsargument,sortedaccordingtothekeys’naturalordering.

1
Mapmap=
new
HashMap();
2
SortedMapsortedMap=
new
TreeMap(map);
Aconstructorwithasingleargumentoftype
SortedMap
,whichcreatesanew
SortedMap
withthesamekey-valuemappingsandthesameorderingastheinput
SortedMap
.

1
SortedMapsortedMap=
new
TreeMap();
2
SortedMapnewSortedMap=
new
TreeMap(sortedMap);

1.SortedMapOperations:

The
SortedMap
interfaceprovidesoperationsfornormalMapoperationsandforthefollowing:

Rangeview—performsarbitraryrangeoperationsonthe
SortedMap

subMap(KfromKey,KtoKey)
:Returnsaviewoftheportionofthis
Map
whosekeysrangefromfromKey,inclusive,totoKey,exclusive.

headMap(KtoKey)
:Returnsaviewoftheportionofthis
Map
whosekeysarestrictlylessthantoKey.

tailMap(KfromKey)
:Returnsaviewoftheportionofthis
Map
whosekeysaregreaterthanorequaltofromKey.

Endpoints—returnsthefirstorthelastkeyinthe
SortedMap

firstKey()
:Returnsthefirst(lowest)keycurrentlyinthis
Map
.

lastKey()
:Returnsthelast(highest)keycurrentlyinthis
Map
.

Comparatoraccess—returnsthe
Comparator
,ifany,usedtosortthemap
comparator()
:Returnsthe
Comparator
usedtoorderthekeysinthis
Map
,ornullifthis
Map
usesthenaturalorderingofitskeys.

2.Example:

2.1.SortMapExample.java

01
package
com.jcg.util.map;
02
03
import
java.util.Comparator;
04
import
java.util.HashMap;
05
import
java.util.Map;
06
import
java.util.TreeMap;
07
08
/**
09
*@authorashraf
10
*
11
*/
12
public
class
SortMapExample{
13
14
/**
15
*Themainmethod.
16
*
17
*@paramargsthearguments
18
*/
19
public
static
void
main(String[]args){
20
//creatingunsortedmapofemployeeidasakeyandemployeenameasavalue
21
MapunsortMap=
new
HashMap();
22
unsortMap.put(
10
,
"Ashraf"
);
23
unsortMap.put(
5
,
"Sara"
);
24
unsortMap.put(
6
,
"Mohamed"
);
25
unsortMap.put(
20
,
"Esraa"
);
26
unsortMap.put(
1
,
"Bahaa"
);
27
unsortMap.put(
7
,
"Dalia"
);
28
unsortMap.put(
8
,
"Amira"
);
29
unsortMap.put(
99
,
"Ahmed"
);
30
unsortMap.put(
50
,
"Sama"
);
31
unsortMap.put(
2
,
"Nada"
);
32
unsortMap.put(
9
,
"Osama"
);
33
34
System.out.println(
"UnsortMap......"
);
35
printMap(unsortMap);
36
37
//UsingthedefaultnaturalorderingofsortedmapIntegerkeywhichimplementComparableinterface
38
System.out.println(
"\nSortedMapinascendingorder......"
);
39
MapascSortedMap=
new
TreeMap();
40
ascSortedMap.putAll(unsortMap);
41
printMap(ascSortedMap);
42
43
//Forcingthedescendingorderbycreatingourowncomparatorthenpassingittothesortedmapatcreationtime
44
System.out.println(
"\nSortedMapindescendingorder......"
);
45
MapdesSortedMap=
new
TreeMap(
46
new
Comparator(){
47
48
@Override
49
public
int
compare(Integero1,Integero2){
50
return
o2.compareTo(o1);
51
}
52
53
});
54
desSortedMap.putAll(unsortMap);
55
printMap(desSortedMap);
56
57
}
58
59
/**
60
*Printsthemap.
61
*
62
*@parammapthemap
63
*/
64
public
static
void
printMap(Mapmap){
65
for
(Map.Entryentry:map.entrySet()){
66
System.out.println(
"Key:"
+entry.getKey()+
"Value:"
67
+entry.getValue());
68
}
69
}
70
71
}

2.2.Explanation:

Let’ssupposethatwewanttosorta
Map
whichcontainsagroupofemployeesaccordingtotheiridswhereweusetheemployeeidasakeyandtheemployeenameasavalue.Afterwecreatea
SortedMap
usingthis
Map
andthekeyofthis
Map
isan
Integer
typewhichimplementsthe
Comparable
interface,thekeysareorderedintheirnaturalordering.Also,wecanapplythedescendingorderbycreatingourown
Comparator
thenpassingittothe
SortedMap
atcreationtime.

2.3.Output:

viewsourceprint?

01
UnsortMap......
02
Key:50Value:Sama
03
Key:1Value:Bahaa
04
Key:2Value:Nada
05
Key:99Value:Ahmed
06
Key:20Value:Esraa
07
Key:5Value:Sara
08
Key:6Value:Mohamed
09
Key:7Value:Dalia
10
Key:8Value:Amira
11
Key:9Value:Osama
12
Key:10Value:Ashraf
13
14
SortedMapinascendingorder......
15
Key:1Value:Bahaa
16
Key:2Value:Nada
17
Key:5Value:Sara
18
Key:6Value:Mohamed
19
Key:7Value:Dalia
20
Key:8Value:Amira
21
Key:9Value:Osama
22
Key:10Value:Ashraf
23
Key:20Value:Esraa
24
Key:50Value:Sama
25
Key:99Value:Ahmed
26
27
SortedMapindescendingorder......
28
Key:99Value:Ahmed
29
Key:50Value:Sama
30
Key:20Value:Esraa
31
Key:10Value:Ashraf
32
Key:9Value:Osama
33
Key:8Value:Amira
34
Key:7Value:Dalia
35
Key:6Value:Mohamed
36
Key:5Value:Sara
37
Key:2Value:Nada
38
Key:1Value:Bahaa
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: