java.util.concurrent.ConcurrentNavigableMap
接口是 java.util.NavigableMap的一个子接口支持并发访问 ,也为其子map提供了并发访问。子map是可以通过多个方法返回的map例如, headMap()
, subMap()
和tailMap()
.
这里只解释 ConcurrentNavigableMap
中新加的方法,其他的方法可以参考NavigableMap
。
headMap()
headMap(T toKey)方法返回小于给定键的键的映射视图。
如果改变原来的map,这些变化也会影响head map.
下面例子说明了headMap()
方法的用法:
package com.ck.thread;
import static org.junit.jupiter.api.Assertions.*;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
import org.junit.jupiter.api.Test;
class ConcurrentNavigableMapTest {
@Test
void test() {
ConcurrentNavigableMap map = new ConcurrentSkipListMap();
map.put("1", "one");
map.put("2", "two");
map.put("3", "three");
ConcurrentNavigableMap headMap = map.headMap("2");
Set<String> keySet = headMap.keySet();
for(String key : keySet) {
System.out.println("key:" + key +" , value:" + headMap.get(key));
}
}
}
运行结果:
key:1 , value:one
headMap
将指向只包含key为1的ConcurrentNavigableMap
, 因为只有这个键严格小于“2”。
可以查看JavaDoc了解更多的关于整个方法的细节,以及它的重载版本如何工作。
tailMap()
tailMap(T fromKey)
方法将返回包含或者大于fromKey的map视图
.
如果改变原来的map,这些变化也会影响tail map。
下面例子说明了tailMap ()
方法的用法
package com.ck.thread;
import static org.junit.jupiter.api.Assertions.*;
import java.util.Set;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
import org.junit.jupiter.api.Test;
class ConcurrentNavigableMapTest {
@Test
void test() {
ConcurrentNavigableMap map = new ConcurrentSkipListMap();
map.put("1", "one");
map.put("2", "two");
map.put("3", "three");
ConcurrentNavigableMap headMap = map.tailMap("2");
Set<String> keySet = headMap.keySet();
for(String key : keySet) {
System.out.println("key:" + key +" , value:" + headMap.get(key));
}
}
}
运行结果:
key:2 , value:two
key:3 , value:three
tailMap
包含了 keys "2"
和"3"
,因为这两个key大于等于给定的key”2”.
可以查看JavaDoc了解更多的关于整个方法的细节,以及它的重载版本如何工作。
subMap()
subMap()
方法返回了一个从from (including)到to (excluding)的map试图,并且key大于等于from小于to,下面是个例子:
package com.ck.thread;
import static org.junit.jupiter.api.Assertions.*;
import java.util.Set;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
import org.junit.jupiter.api.Test;
class ConcurrentNavigableMapTest {
@Test
void test() {
ConcurrentNavigableMap map = new ConcurrentSkipListMap();
map.put("1", "one");
map.put("2", "two");
map.put("3", "three");
ConcurrentNavigableMap headMap = map.subMap("2", "3");
Set<String> keySet = headMap.keySet();
for(String key : keySet) {
System.out.println("key:" + key +" , value:" + headMap.get(key));
}
}
}
运行结果:
key:2 , value:two
返回的submap contains 只有 key为"2"
, 因为大于等于,小样 "3"
.
更多方法
ConcurrentNavigableMap
接口包含了更多的可用方法,例如
:
- descendingKeySet()
- descendingMap()
- navigableKeySet()
更多的方法信息可以参考官方的javaDoc.
参考翻译:http://tutorials.jenkov.com/java-util-concurrent/concurrentnavigablemap.html