Guava学习笔记-预览迭代器中的下一个元素

原创
2016/01/23 16:48
阅读数 192

###问题描述:
去除List中连续的重复元素
["1","1","1","2”,"2","3","4"]->["1","2","3","4"]
[]->[]

###原来

List<String> result = Lists.newArrayList();
Iterator<String> iterator = source.iterator();
String current = null;
while (iterator.hasNext()) {
    if (current == null) {
        current = iterator.next();
    }
    result.add(current);
    while (iterator.hasNext()) {
        String next = iterator.next();
        if (current.equals(next)) {
            continue;
        }
        current = next;
        break;
    }
}
if (current != null && !result.get(result.size() - 1).equals(current)) {
    result.add(current);
}

因为需要在下一个元素与当前元素不相等的时候保留上一个元素,所以写起来比较复杂用了两层循环,并且容易写错,改了好几遍才通过测试用例

###使用Guava

List<String> result = Lists.newArrayList();
PeekingIterator<String> iterator = Iterators.peekingIterator(source.iterator());
String current = null;
while (iterator.hasNext()) {
    if (!iterator.peek().equals(current)) {
        current = iterator.next();
        result.add(current);
    } else {
        iterator.next();
    }
}

使用PeekingIterator,代码精简许多,也更易于理解,也不容易写错
需要注意的是,如果没有下一个元素了,使用iterator.peek()会抛出异常

展开阅读全文
打赏
1
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
1
分享
返回顶部
顶部