在java平常开发中,常常须要使用各类数据结构,在涉及到数据结构之间如何优雅的转换时,咱们能够借助google的guava提供的相关功能来优雅的实现。如下记录一些开发中常常须要使用数据结构的变形,以便使用时方便查阅。 通常咱们的数据结构中存储的为对象,如下举例先构造一个类,用来存放中不一样的数据结构中。java
class Person { public String name; public int age; Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return MoreObjects.toStringHelper(this).omitNullValues() .add("name", name) .add("age", age) .toString(); } }
提供一个方法来构造一个对象list数据结构
public static Collection<Person> queryPersion(){ return Lists.newArrayList( new Person("kang",30), new Person("liu",25), new Person("han",22) ); } //某个属性为null public static List<Person> queryPersion2(){ return Lists.newArrayList( new Person("kang",30), new Person("liu",25), new Person("han",22), new Person(null,24) ); }
List<Person> persons = queryPersion(); List<String> peopleNames = Lists.transform(persons, new Function<Person, String>() { @Override public String apply(Person person) { return person.getName(); } });
Collection<Person> matchingPersons = queryPersion2(); Collection<String> peopleNames = Lists.newArrayList( Iterables.filter( Iterables.transform(matchingPersons, new Function<Person, String>() { @Override public String apply(Person from) { return from.getName(); } }), Predicates.notNull() ) );
Collection<Person> persons = queryPersion(); List<Person> oldPeople = Lists.newArrayList(Iterables.filter(persons, new Predicate<Person>() { public boolean apply(Person person) { return person.getAge() >= 25; } }));
//name重复或者name为null时会报错 Collection<Person> yourList = queryPersion(); Map<String,Person> mappeds = Maps.uniqueIndex(yourList, new Function<Person,String>() { @Nullable public String apply(Person from) { // do stuff here return from.getName(); }});
Collection<Person> yourList = queryPersion(); ImmutableListMultimap<String, Person> mapping = Multimaps.index(yourList, new Function<Person,String>() { public String apply(Person input) { return input.getName(); } });
Lists.newArrayListWithExpectedSize(size);