当前位置: 代码迷 >> 综合 >> guava(java第三方工具类库)
  详细解决方案

guava(java第三方工具类库)

热度:54   发布时间:2024-02-11 18:51:28.0

guava是什么

Guava是Java项目广泛第三方库,其中包括:集合 、缓存 、原生类型支持 、并发库 、通用注解 、字符串处理 、I/O 等等。 所有这些工具每天都在被java工程b师应用在业务服务中。

集合

再jdk1.7之前,原生jdk对集合操作并不友好,使用guava的集合很大程度上方便了我们对集合的操作。

不可变集合

新集合类型

Multiset

很方便获取集合中元素的个数

public static void main(String[] args) {//此时也是使用guava 很方便吧,直接可以复制,不用在,泛型使用的也更加简单了// List<String> strings = Arrays.asList("a", "b", "c", "d", "e", "f", "a", "c", "d", "a");//原始方法求集合中元素的个数List<String> strings = Lists.newArrayList("a", "b", "c", "d", "e", "f", "a", "c", "d", "a");Map<String, Integer> countMap = Maps.newHashMap();for (String string : strings) {if (countMap.containsKey(string)){Integer count = countMap.get(string);countMap.put(string,++count);}else {countMap.put(string,1);}}System.out.println(new Gson().toJson(countMap));//使用guava的新集合Multiset multiset = HashMultiset.create();//求交集multiset.addAll(strings);System.out.println("新集合元素:"+multiset);System.out.println("a的次数:"+ multiset.count("a"));System.out.println("c的次数:"+multiset.count("c"));System.out.println("f的次数:"+multiset.count("f"));//还可以自定义设置参数multiset.setCount("a",1000);System.out.println(multiset);System.out.println("a的次数:"+ multiset.count("a"));}

ListMultimap

list集合分组

 public static void main(String[] args) {//list转map,分别计算出3年级与2年级的学生信息//传统做法Student student = new Student(19,"王强" , 1, 3);Student student1 = new Student(18,"张强" , 1, 2);Student student2 = new Student(18,"李静" , 2, 2);Student student3 = new Student(19,"王萍" , 1, 3);List<Student> strings = Lists.newArrayList(student,student1,student2,student3);Map<Integer, List<Student>> studentMap = Maps.newHashMap();for (Student string : strings) {if (studentMap.containsKey(string.getGrade())){List<Student> students = studentMap.get(string.getGrade());students.add(string);}else {List<Student> objects = Lists.newArrayList();objects.add(string);studentMap.put(string.getGrade(),objects);}}System.out.println(new Gson().toJson(studentMap));System.out.println("****************************************************guava分割**************************************************************");//第一个泛型就是分组的key 第二个泛型就是集合的类型ListMultimap<Integer, Student> build = MultimapBuilder.treeKeys().arrayListValues().build();for (Student string : strings) {//一行代码就搞定build.put(string.getGrade(),string);}//转成map同上面相同System.out.println("转map:"+new Gson().toJson(build.asMap()));System.out.println("班级2集合:"+new Gson().toJson(build.get(2)));System.out.println("班级3集合:"+new Gson().toJson(build.get(3)));//删除班级2的王强boolean remove = build.remove(2, student1);System.out.println("删除班级2的张强转map:"+new Gson().toJson(build.asMap()));//删除班级3的所有人List<Student> students = build.removeAll(3);System.out.println("删除班级3的所有人转map:"+new Gson().toJson(build.asMap()));}

未完待续

  相关解决方案