美文网首页
创建只读的 Lists, Sets, and Maps

创建只读的 Lists, Sets, and Maps

作者: freeseawind | 来源:发表于2018-07-09 23:17 被阅读0次
开发环境
  • eclipse 4.7.3a
  • jdk 9
主题
  • 关于只读集合
  • 只读集合API
  • 复制已有集合到不只读集合中
  • 从Streams创建只读集合
  • 随机迭代顺序
关于只读集合

不可变方法的常见场景是一个从已知值初始化的集合,它永远不会更改。只读变集合存储一个永不改变的数据集 (类似于常量集合),这样可以利用性能和节省空间的优势。

只读集合 API 介绍
List

API 方法如下:

List.of()
List.of(e1)
List.of(e1, e2)         // fixed-argument form overloads up to 10 elements
List.of(elements...)   // varargs form supports an arbitrary number of elements or an array

JDK 1.8 例子

List<String> stringList = Arrays.asList("a", "b", "c");
stringList = Collections.unmodifiableList(stringList);

JDK 1.9 例子

List stringList = List.of("a", "b", "c");
Set

API 方法如下:

Set.of()
Set.of(e1)
Set.of(e1, e2)         // fixed-argument form overloads up to 10 elements
Set.of(elements...)   // varargs form supports an arbitrary number of elements or an array

JDK 1.8 例子

Set<String> stringSet = new HashSet<>(Arrays.asList("a", "b", "c"));
stringSet = Collections.unmodifiableSet(stringSet);

JDK 1.9 例子

Set<String> stringSet = Set.of("a", "b", "c");
Map

API 方法如下:

Map.of()
Map.of(k1, v1)
Map.of(k1, v1, k2, v2)    // fixed-argument form overloads up to 10 key-value pairs
Map.ofEntries(entry(k1, v1), entry(k2, v2),...)
 // varargs form supports an arbitrary number of Entry objects or an array

JDK 1.8 例子

Map<String, Integer> stringMap = new HashMap<String, Integer>(); 
stringMap.put("a", 1); 
stringMap.put("b", 2);
stringMap.put("c", 3);
stringMap = Collections.unmodifiableMap(stringMap);

JDK 1.9 例子

Map stringMap = Map.of("a", 1, "b", 2, "c", 3);

通过entry方式创建Map

import static java.util.Map.entry;
Map <Integer, String> friendMap = Map.ofEntries(
   entry(1, "Tom"),
   entry(2, "Dick"),
   entry(3, "Harry"),
   ...
   entry(99, "Mathilde"));
复制已有的集合
 List<Item> snapshot = List.copyOf(list); 
// Map.copyOf(map)
// Set.copyOf(set)
从Streams创建只读集合

如果要保证返回的集合是不可变的,则应使用toUnmodifiable-collector之一。 这些API是:

Collectors.toUnmodifiableList()
Collectors.toUnmodifiableSet()
Collectors.toUnmodifiableMap(keyMapper, valueMapper)     
Collectors.toUnmodifiableMap(keyMapper, valueMapper, mergeFunction)

例如,要转换源集合的元素并将结果放入只读集合,可以执行以下操作:

Set<Item> immutableSet =
      sourceCollection.stream()
                      .map(...) 
                      .collect(Collectors.toUnmodifiableSet());
随机迭代顺序

由Set.of,Map.of和Map.ofEntries方法创建的集合实例迭代顺序随机化。

jshell> Map stringMap = Map.of("a", 1, "b", 2, "c", 3);
stringMap ==> {b=2, c=3, a=1}

jshell> Map stringMap = Map.of("a", 1, "b", 2, "c", 3);
stringMap ==> {b=2, c=3, a=1}

jshell> /exit
|  Goodbye

C:\Program Files\Java\jdk-9\bin>jshell
|  Welcome to JShell -- Version 9-ea
|  For an introduction type: /help intro

jshell> Map stringMap = Map.of("a", 1, "b", 2, "c", 3);
stringMap ==> {a=1, b=2, c=3}

Github工程地址

相关文章

网友评论

      本文标题:创建只读的 Lists, Sets, and Maps

      本文链接:https://www.haomeiwen.com/subject/jvrxpftx.html