Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.moozvine.strings;
- import com.google.common.collect.ImmutableList;
- import java.util.Iterator;
- import java.util.List;
- import java.util.NoSuchElementException;
- public final class LineIterator {
- private LineIterator(){}
- public static Iterator<String> of(final String value) {
- final List<String> lines = ImmutableList.copyOf(value.split("\n"));
- return lines.iterator();
- }
- public static Iterable<String> toIterable(final String value) {
- return new Iterable<String>() {
- @Override public Iterator<String> iterator() {
- return of(value);
- }
- };
- }
- public static Iterator<String> of(final StringBuilder value) {
- return new Iterator<String>() {
- boolean hasNext = true;
- boolean removed = false;
- int start = 0;
- int end = -1;
- @Override public boolean hasNext() {
- return hasNext;
- }
- @Override public String next() {
- removed = false;
- if (!hasNext) {
- throw new NoSuchElementException();
- }
- start = end + 1;
- end = value.indexOf("\n", start);
- if (end == -1) {
- hasNext = false;
- }
- return value.substring(
- start,
- end == -1 ? value.length() : end);
- }
- @Override public void remove() {
- if (removed) {
- throw new IllegalStateException("Multiple calls to remove() without and intervening call to next().");
- }
- value.delete(
- start,
- end == -1 ? value.length() : end + 1);
- end = start - 1;
- removed = true;
- }
- };
- }
- public static Iterable<String> toIterable(final StringBuilder value) {
- return new Iterable<String>() {
- @Override public Iterator<String> iterator() {
- return of(value);
- }
- };
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement