标签:
***********************************************声明******************************************************
原创作品,出自 “晓风残月xj” 博客,欢迎转载,转载时请务必注明出处(http://blog.csdn.net/xiaofengcanyuexj)。
由于各种原因,可能存在诸多不足,欢迎斧正!
*********************************************************************************************************
RangeMap是一种集合类型,它将不相交、且不为空的Range(key)映射给一个值(Value),RangeMap不可以将相邻的区间合并,即使这个区间映射的值是一样的,实现RangeMap也是一个接口,实现它的也只有两个类,分别为mmutableRangeMap和TreeRangeMap。其中TreeRangeMap是key有序的。具体区间排序规则就不再说了。
private static void testRangeMap() { RangeMap<Integer, String> rangeMap = TreeRangeMap.create(); rangeMap.put(Range.closed(1, 10), "aaa"); System.out.println(rangeMap); rangeMap.put(Range.open(3, 6), "bbb"); System.out.println(rangeMap); rangeMap.put(Range.openClosed(10, 20), "aaa"); System.out.println(rangeMap); rangeMap.put(Range.closed(20, 20), "aaa"); System.out.println(rangeMap); rangeMap.remove(Range.closed(5, 11)); System.out.println(rangeMap); } 输入结果为: [[1‥10]=aaa] [[1‥3]=aaa, (3‥6)=bbb, [6‥10]=aaa] [[1‥3]=aaa, (3‥6)=bbb, [6‥10]=aaa, (10‥20]=aaa] [[1‥3]=aaa, (3‥6)=bbb, [6‥10]=aaa, (10‥20)=aaa, [20‥20]=aaa] [[1‥3]=aaa, (3‥5)=bbb, (11‥20)=aaa, [20‥20]=aaa] 遍历RangeMap的方法 private static void printToConsole(TreeRangeMap<Item, Integer> rangeMap) { Map<Range<Item>, Integer> rangeStringMap = rangeMap.asMapOfRanges(); Set<Map.Entry<Range<Item>, Integer>> entries = rangeStringMap.entrySet(); for (Map.Entry<Range<Item>, Integer> next : entries) { Item left = next.getKey().lowerEndpoint(); Item right = next.getKey().upperEndpoint(); String lines = left + "~" + right + " " + next.getValue(); System.out.println(lines); } }
Range区间的自定义对象必须实现Comparable接口,这样才能保证进行区间的划分。如下
/** * 日期类,存放年月日 */ public class Item implements Comparable<Item> { private int year, month, day; public Item(int ye, int mon, int da) { this.year = ye; this.month = mon; this.day = da; } public Item() { } public void setItem(Item item) { this.year = item.year; this.month = item.month; this.day = item.day; } @Override public int compareTo(Item item) { if (this.year < item.year) return -1; else if (this.year == item.year) { if (this.month < item.month) return -1; else if (this.month == item.month) { if (this.day < item.day) return -1; else if (this.day == item.day) return 0; else return 1; } else return 1; } else return 1; } public String toString() { String date = ""; if (0 == this.month / 10) date = this.year + "-" + "0" + this.month; else date = this.year + "-" + this.month; if (0 == this.day / 10) date = date + "-" + "0" + this.day; else date = date + "-" + this.day; return date; } }
由于时间有限,在写博文的过程中参考过一些文献,在此表示感谢;同时鉴于水平原因,你难免有不足之处,欢迎斧正!
标签:
原文地址:http://blog.csdn.net/xiaofengcanyuexj/article/details/44498951