经验不在于年限,在于积累---专注互联网软件开发

把工作当事业做,把项目当作品做!

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  55 Posts :: 0 Stories :: 66 Comments :: 0 Trackbacks
  1package googleCollections;
  2
  3import java.util.ArrayList;
  4import java.util.Collection;
  5import java.util.HashMap;
  6import java.util.List;
  7import java.util.Map;
  8
  9import com.google.common.collect.ArrayListMultimap;
 10import com.google.common.collect.ConcurrentHashMultiset;
 11import com.google.common.collect.Multimap;
 12import com.google.common.collect.Multiset;
 13
 14/**
 15 * Copyright (C): 2009
 16 * @author 陈新汉 http://www.blogjava.net/hankchen
 17 * @version 创建时间:Jan 12, 2010 11:55:49 PM
 18 */

 19
 20/**
 21 * 模拟测试情形:描述每个学生有多本书籍
 22 * 
 23 * Multimap适合保存柱状图的数据
 24 */

 25public 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("数学"));
 39        studentBook.put(me,books);
 40        //遍历
 41        for(Book b:books){
 42            System.out.println(b.getName());
 43        }

 44        
 45        /**
 46         * 现在的方式
 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("数学"));
 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可以允许重复值
 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
 74class 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
 89class 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

(友情提示:本博文章欢迎转载,但请注明出处:hankchen,http://www.blogjava.net/hankchen

posted on 2010-01-13 00:51 hankchen 阅读(1804) 评论(0)  编辑  收藏 所属分类: Java基础

只有注册用户登录后才能发表评论。


网站导航: