分段刷新追加缓存实现

2016-11-18  本文已影响0人  kangqiao182

最近项目中有一个需求, 要对原有的缓存列表做分段刷新操作.

具体需求如下
oldCache : "... , 00, 10, 20, 30, 40" //原有数据缓存
newCache: "00, 10, 20, 30, 40, 50, 60" //新刷新的数据片段
要求新数据片段更新到原先的缓存中. 并且更新最后相等的元素.
结果:
"... , 00, 10, 20, 30, 40, 50, 60"
其中的40, 50, 60元素来自新刷新的数据.

实现如下:

    public static void main(String args[]){
        List<String> oldList = new ArrayList<>();
        //oldList.add("06_old_0");
        oldList.add("00_old_0");
        oldList.add("10_old_1");
        oldList.add("20_old_2");
        oldList.add("30_old_3");
        oldList.add("40_old_4");
        oldList.add("41_old_4");

        List<String> newList = new ArrayList<>();
        newList.add("05_new_0");
        newList.add("10_new_1");
        newList.add("20_new_2");
        newList.add("30_new_3");
        newList.add("40_new_4");
        newList.add("42_new_4");
        newList.add("50_new_5");
        //newList.add("60_new_5");
        //newList.add("70_new_5");

        int oldLastIndex = oldList.size() - 1;
        int startRefreshIndex = newList.size() - 1;
        String oldLastDateStr = oldLastIndex < 0? "-1": oldList.get(oldLastIndex).substring(0,2);
        for(int i=startRefreshIndex; i >= 0; i--){
            int ni = Integer.parseInt(newList.get(i).substring(0,2));
            int oi = Integer.parseInt(oldLastDateStr);
            int ret = ni - oi;
            if(ret > 0){
                startRefreshIndex = i - 1;
            } else if( ret == 0){
                oldList.set(oldLastIndex, newList.get(startRefreshIndex)+">>");
                startRefreshIndex++;
                break;
            } else{
                startRefreshIndex++;
                break;
            }
        }

        startRefreshIndex = Math.max(0, startRefreshIndex);
        for(; startRefreshIndex<newList.size(); startRefreshIndex++){
            oldList.add(newList.get(startRefreshIndex));
        }

        System.out.println("oldList = [" + oldList + "]");
    }

运行结果:

oldList = [[00_old_0, 10_old_1, 20_old_2, 30_old_3, 40_old_4, 41_old_4, 42_new_4, 50_new_5]]
上一篇 下一篇

猜你喜欢

热点阅读