###问题描述:
去除List中连续的重复元素 ["1","1","1","2”,"2","3","4"]->["1","2","3","4"] []->[]###原来
Listresult = Lists.newArrayList();Iterator 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
Listresult = Lists.newArrayList();PeekingIterator 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()会抛出异常