Guava学习之Map

Guava 中文是石榴的意思,该项目是 Google 的一个开源项目,包含许多 Google 核心的 Java 常用库。

目前主要包含:

  • com.google.common.annotations
  • com.google.common.base
  • com.google.common.collect
  • com.google.common.io
  • com.google.common.net
  • com.google.common.primitives
  • com.google.common.util.concurrent

    在线API doc:http://tool.oschina.net/apidocs/apidoc?api=guava

现有如下Person类:

public class Person {

    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name=‘" + name + ‘\‘‘ +
                ", age=" + age +
                ‘}‘;
    }
}

1 将List转化为Map

1.1 转化后具有唯一Key

public class TestMap {
    public static void main(String args[]) {
        List<Person> persons = Arrays.asList(
                new Person("zhang", 15),
                new Person("wang", 16),
                new Person("lee", 18)
        );
        /**
         * 转换后的Map具有唯一键
         */
        Map<String, Person> map = Maps.uniqueIndex(persons, new Function<Person, String>() {
            @Override
            public String apply(Person person) {
                return person.getName();
            }
        });
    }

}

1.2 转化后的Key不唯一

public class TestMap {
    public static void main(String args[]) {
        List<Person> persons = Lists.newArrayList(
                new Person("zhang", 15),
                new Person("zhang", 16),
                new Person("lee", 18)
        );
        /**
         * 转换后的Map有重复键
         */
        Multimap<String, Person> multiMap = Multimaps.index(persons, new Function<Person, String>() {
            public String apply(Person person) {
                return person.getName();
            }
        });
    }
}

2 将Set转化为Map

public class TestMap {
    public static void main(String args[]) {
        Set<Person> persons = Sets.newHashSet(
                new Person("zhang", 15),
                new Person("zhang", 16),
                new Person("lee", 18)
        );
        /**
         * 以Set的值为Key,计算出一个Value
         */
        Map<Person, String> map = Maps.asMap(persons, new Function<Person, String>() {
            public String apply(Person person) {
                return person.getName();
            }
        });
    }
}

3 转换Map的值

public class TestMap {

    public static void main(String args[]) {
        List<Person> persons = Lists.newArrayList(
                new Person("zhang", 15),
                new Person("wang", 15),
                new Person("lee", 18)
        );
        Map<String, Person> map = Maps.uniqueIndex(persons, new Function<Person, String>() {
            public String apply(Person person) {
                return person.getName();
            }
        });

        /**
         * 使用Key和Value作为输入,计算出一个新的Value
         */
        Map<String, Integer> map2 = Maps.transformEntries(map, new Maps.EntryTransformer<String, Person, Integer>() {
            @Override
            public Integer transformEntry(String s, Person person) {
                return person.getAge();
            }
        });

        /**
         * 使用Function计算出一个新的Value
         */
        Map<String, Double> map3 = Maps.transformValues(map, new Function<Person, Double>() {
            @Override
            public Double apply(Person person) {
                return (double)person.getAge();
            }
        });
    }
}

4 筛选Map中符合条件的映射

public class TestMap {

    public static void main(String args[]) {
        List<Person> persons = Lists.newArrayList(
                new Person("zhang", 15),
                new Person("wang", 15),
                new Person("lee", 18)
        );
        Map<String, Person> map = Maps.uniqueIndex(persons, new Function<Person, String>() {
            public String apply(Person person) {
                return person.getName();
            }
        });

        map = Maps.filterEntries(map, new Predicate<Map.Entry<String, Person>>() {
            @Override
            public boolean apply(Map.Entry<String, Person> stringPersonEntry) {
                return stringPersonEntry.getKey() != null && stringPersonEntry.getValue() != null;
            }
        });

        map = Maps.filterKeys(map, new Predicate<String>() {
            @Override
            public boolean apply(String s) {
                return s != null && s.length() > 2;
            }
        });

        map = Maps.filterValues(map, new Predicate<Person>() {
            @Override
            public boolean apply(Person person) {
                return person != null && person.getAge() > 15;
            }
        });

        for (Map.Entry<String, Person> entry : map.entrySet()) {
            System.out.println(entry.getKey() + " " + entry.getValue());
        }
    }
}
时间: 2024-08-12 14:01:09

Guava学习之Map的相关文章

Guava学习笔记:Multimaps

Guava学习笔记:Multimaps 有时候我们需要这样的数据类型Map<String,Collection<String>>,guava中的Multimap就是为了解决这类问题的. Multimap的实现 Multimap提供了丰富的实现,所以你可以用它来替代程序里的Map<K, Collection<V>>,具体的实现如下: 实现 Key实现 Value实现 ArrayListMultimap HashMap ArrayList HashMultima

Guava学习笔记: BiMap

Guava学习笔记: BiMap 我们知道Map是一种键值对映射,这个映射是键到值的映射,而BiMap首先也是一种Map,他的特别之处在于,既提供键到值的映射,也提供值到键的映射,所以它是双向Map. 想象这么一个场景,我们需要做一个星期几的中英文表示的相互映射,例如Monday对应的中文表示是星期一,同样星期一对应的英文表示是Monday.这是一个绝好的使用BiMap的场景. package cn.outofmemory.guava.collection; import com.google.

Guava学习笔记:guava中对字符串的操作

Guava学习笔记:guava中对字符串的操作 转载:http://outofmemory.cn/java/guava/base/Strings 在google guava中为字符串操作提供了很大的便利,有老牌的判断字符串是否为空字符串或者为null,用指定字符填充字符串,以及拆分合并字符串,字符串匹配的判断等等. 下面我们逐一了解这些操作: 1. 使用com.google.common.base.Strings类的isNullOrEmpty(input)方法判断字符串是否为空        

[Guava学习笔记]Collections: 不可变集合, 新集合类型

不可变集合 不接受null值. 创建:ImmutableSet.copyOf(set); ImmutableMap.of(“a”, 1, “b”, 2); public static final ImmutableSet<Color> GOOGLE_COLORS = ImmutableSet.<Color>builder() .addAll(WEBSAFE_COLORS) .add(new Color(0, 191, 255)) .build(); 可以有序(如ImmutableS

iOS学习之Map,定位,标记位置的使用

iOS上使用地图比Android要方便,只需要新建一个MKMapView,addSubView即可.这次要实现的效果如下: 有标注(大头针),定位,地图. 1.添加地图 1.1 新一个Single View app ,选择默认项,创建后,在ViewController.h [cpp] view plaincopy #import <UIKit/UIKit.h> #import <MapKit/MapKit.h> #import <CoreLocation/CoreLocati

Guava学习笔记:Google Guava 类库简介

> Guava 是一个 Google 的基于java1.6的类库集合的扩展项目,包括 collections, caching, primitives support, concurrency libraries, common annotations, string processing, I/O, 等等. 这些高质量的 API 可以使你的JAVa代码更加优雅,更加简洁,让你工作更加轻松愉悦.下面我们就开启优雅Java编程学习之旅! 项目相关信息: 官方首页:http://code.googl

Guava学习笔记:guava中的Preconditions使用

Guava学习笔记:guava中的Preconditions使用 转载:http://outofmemory.cn/java/guava/base/Preconditions google guava的base包中提供的Preconditions类用来方便的做参数的校验,他主要提供如下方法: checkArgument 接受一个boolean类型的参数和一个可选的errorMsg参数,这个方法用来判断参数是否符合某种条件,符合什么条件google guava不关心,在不符合条件时会抛出Illeg

Guava学习笔记: guava集合之Multiset

Guava学习笔记: guava集合之Multiset Multiset是什么? Multiset看似是一个Set,但是实质上它不是一个Set,它没有继承Set接口,它继承的是Collection<E>接口,你可以向Multiset中添加重复的元素,Multiset会对添加的元素做一个计数. 它本质上是一个Set加一个元素计数器. Multiset使用示例: package cn.outofmemory.guava.collection; import com.google.common.ba

Guava学习笔记:guava的不可变集合

Guava学习笔记:guava的不可变集合 不可变集合的意义 不可变对象有很多优点,包括: 当对象被不可信的库调用时,不可变形式是安全的: 不可变对象被多个线程调用时,不存在竞态条件问题 不可变集合不需要考虑变化,因此可以节省时间和空间.所有不可变的集合都比它们的可变形式有更好的内存利用率(分析和测试细节): 不可变对象因为有固定不变,可以作为常量来安全使用. 创建对象的不可变拷贝是一项很好的防御性编程技巧.Guava为所有JDK标准集合类型和Guava新集合类型都提供了简单易用的不可变版本.