1
package googleCollections;
2
3
import java.util.ArrayList;
4
import java.util.Collection;
5
import java.util.HashMap;
6
import java.util.List;
7
import java.util.Map;
8
9
import com.google.common.collect.ArrayListMultimap;
10
import com.google.common.collect.ConcurrentHashMultiset;
11
import com.google.common.collect.Multimap;
12
import com.google.common.collect.Multiset;
13
14
/**
15
* Copyright (C): 2009
16
* @author 陳新漢 http://www.aygfsteel.com/hankchen
17
* @version 創(chuàng)建時(shí)間:Jan 12, 2010 11:55:49 PM
18
*/
19
20
/**
21
* 模擬測試情形:描述每個(gè)學(xué)生有多本書籍
22
*
23
* Multimap適合保存柱狀圖的數(shù)據(jù)
24
*/
25
public class MultiCollectionsTest {
26
27
/**
28
* @param args
29
*/
30
public static void main(String[] args) {
31
/**
32
* 以前的方式
33
*/
34
Map<Student, List<Book>> studentBook = new HashMap<Student, List<Book>>();
35
Student me=new Student("chenxinhan");
36
List<Book> books=new ArrayList<Book>();
37
books.add(new Book("語文"));
38
books.add(new Book("數(shù)學(xué)"));
39
studentBook.put(me,books);
40
//遍歷
41
for(Book b:books){
42
System.out.println(b.getName());
43
}
44
45
/**
46
* 現(xiàn)在的方式
47
*/
48
Multimap <Student,Book> newStudentBook = ArrayListMultimap.create();
49
Student cxh=new Student("chenxinhan");
50
newStudentBook.put(cxh,new Book("語文"));
51
newStudentBook.put(cxh,new Book("數(shù)學(xué)"));
52
//遍歷
53
Collection<Book> list=newStudentBook.get(cxh);
54
for(Book b:list){
55
System.out.println(b.getName());
56
}
57
58
/**
59
* Multiset測試
60
* 不同于一般的Set,Multiset可以允許重復(fù)值
61
*/
62
Multiset<Book> bs=ConcurrentHashMultiset.create();
63
Book b=new Book("Test");
64
bs.add(b);
65
bs.add(b);
66
bs.add(b);
67
for(Book ab:bs){
68
System.out.println(ab.getName());
69
}
70
}
71
72
}
73
74
class Student{
75
private String name;
76
77
public String getName() {
78
return name;
79
}
80
public void setName(String name) {
81
this.name = name;
82
}
83
public Student(String name) {
84
this.name = name;
85
}
86
87
}
88
89
class Book{
90
private String name;
91
92
public String getName() {
93
return name;
94
}
95
96
public void setName(String name) {
97
this.name = name;
98
}
99
100
public Book(String name) {
101
this.name = name;
102
}
103
}
104

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

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

(友情提示:本博文章歡迎轉(zhuǎn)載,但請注明出處:hankchen,http://www.aygfsteel.com/hankchen)