区间匹配-(Guava)Range

young 694 2021-10-17

使用场景,用于判断所给信息位于哪个区间范围

Range

常用API

open 开区间 (a,b)

closeed 闭区间 [a,b]

closedOpen 左闭右开 [a,b)

openClosed 左开右闭 (a,b]

lessThan 右开区间 a)

atMost 右闭区间 a]

greaterThan 左开区间 (a

atLeast 左闭区间 [a

contains 查看值是否在区间内

Range<Integer> range = Range.closed(10, 20);
System.out.println(range.contains(15)); // true
System.out.println(range.contains(5));  // false

RangeSet

Range对象的集合
RangeSet rangeSet = TreeRangeSet.create();

常用API

add 添加Range对象

remove 移除Range对象

contains 查看值是否在RangeSet区间内

rangeContaining 获取值所属于的Range对象,匹配不到返回空

TreeRangeSet<Integer> rangeSet = TreeRangeSet.create();
Range<Integer> range = Range.closed(10, 20);
rangeSet.add(range);
System.out.println(rangeSet.contains(5));   // false
System.out.println(rangeSet.contains(15));  // true
System.out.println(rangeSet.rangeContaining(5));  // null
System.out.println(rangeSet.rangeContaining(15)); // 10..20

RangeMap

key为Range对象
RangeMap<Integer,String> rangeMap = TreeRangeMap.create();

常用API

put

get 匹配不上则返回空

RangeMap<Integer,String> rangeMap = TreeRangeMap.create();
Range<Integer> range = Range.closed(10, 20);
rangeMap.put(range,"1");
System.out.println(rangeMap.get(15)); // 1
System.out.println(rangeMap.get(5));  // null