/** * Lists.transform可以很方便将一个集合转换成另外一种类型的集合。 类似于jdk1.8中的map */ @Test public void test7() { /** * 将字符串集合转换为int集合 */ List<String> listStr = Lists.newArrayList("1", "2", "3"); // /** // * listStr:源集合(source); // * function:转换后的集合 // */ // Lists.transform(listStr, new Function<String, Integer>() { // @Nullable // @Override // public Integer apply(@Nullable String s) { // return Integer.valueOf(s); // } // }); List<Integer> collect = listStr.stream().map(Integer::valueOf).collect(Collectors.toList()); System.out.println(collect); } @Test public void test8() { /** * 查找首个匹配的元素 * guava */ List<String> listStr = Lists.newArrayList("hello", "world", "hehe"); String h1 = Iterators.find(listStr.iterator(), new Predicate<String>() { @Override public boolean apply(String s) { return s.startsWith("h"); } }); System.out.println(h1); /** * jdk1.8 */ String h = listStr.stream().findFirst().filter((String s) -> s.startsWith("h")).get(); System.out.println(h); } @Test public void test10() { /** * / 以主键为key,生成键值对:Map<id,Apple></id,Apple> */ List<Apple> appleList = Lists.newArrayList(new Apple(1, "red"), new Apple(2, "red"), new Apple(3, "green"), new Apple(4, "green")); ImmutableMap<Integer, Apple> appleMap = Maps.uniqueIndex(appleList, new Function<Apple, Integer>() { @Override public Integer apply(@Nullable Apple apple) { return apple.getId(); } }); System.out.println(appleList); ImmutableListMultimap<String, Apple> index = Multimaps.index(appleList, new Function<Apple, String>() { @Override public String apply(@Nullable Apple apple) { return apple.getColor(); } }); System.out.println(index); }
guava与jdk1.8
最新推荐文章于 2024-09-13 21:52:04 发布