利用JDK8新的语法糖创建Collection及如何借助 guava 实现语法糖创建Immutable Collection。
guava POM
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
1 利用JDK8新的语法截取list,生成新的subList。
List<String>list=new ArrayList<String>(){{
add("one1");
add("one2");
add("one3");
add("two1");
add("two2");
add("two3");
}};
List<String>subList=list
.stream()
.filter(u ->u.contains("one"))
.collect(Collectors.toList());
System.out.println(subList.toString());
2 如果我们想创建一个不可变的list该怎么做呢
可以把上面的结果用JDK工具包装一下:
List<String> immutableSubList = Collections.unmodifiableList(subList);
System.out.println(immutableSubList);
//throw exception
immutableSubList.add("xx");
这样新返回的list 就是不可变的了。
3 有没有办法直接在下面的.collection()中放一个类似Collectors.toList()的东西,就直接返回一个不可变的对象。
List<String>subList=list
.stream()
.filter(u ->u.contains("one"))
.collect(Collectors.toList());
google了一下可用JDK8的Collector中的of方法来生成所需的东西。
of方法签名如下
/**
* @param supplier 供应函数 来创建List实例
* @param accumulator 把流中的元素添加到上面创建的实例中
* @param combiner 当stream为parallel模式时,把两个实例融合为一个
* @param characteristics collector特点
* @param <T> The type of input elements for the new collector
* @param <A> The intermediate accumulation type of the new collector
* @param <R> The final result type of the new collector
* @throws NullPointerException if any argument is null
* @return the new {@code Collector}
public static<T, A, R> Collector<T, A, R> of(Supplier<A> supplier,
BiConsumer<A, T> accumulator,
BinaryOperator<A> combiner,
Characteristics... characteristics)
根据上面的提示我们写出下面的代码
//创建不可变的list 用的toList
public static <T> Collector<T, ?, ImmutableList<T>> toList() {
return Collector.of(
ImmutableList.Builder::new,
ImmutableList.Builder::add,
(left, right) -> left.addAll(right.build()),
(Function<ImmutableList.Builder<T>, ImmutableList<T>>)
ImmutableList.Builder::build);
}
验证代码
//immutable list
List<String> list = Lists.newArrayList("xx", "yy");
ImmutableList<String> sublist = list
.stream()
.filter(s -> s.contains("xx"))
.collect(toList());
System.out.println(Iterables.getOnlyElement(sublist).equals("xx"));
//throw exception
sublist.add("yy");
结果打印true,并抛出异常。
转发标注来源:http://my.oschina.net/robinyao/blog/469184