Advertisement
Stanbey

LineIterator

Dec 3rd, 2015
480
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.84 KB | None | 0 0
  1. package com.moozvine.strings;
  2.  
  3.  
  4. import com.google.common.collect.ImmutableList;
  5.  
  6. import java.util.Iterator;
  7. import java.util.List;
  8. import java.util.NoSuchElementException;
  9.  
  10. public final class LineIterator {
  11.   private LineIterator(){}
  12.  
  13.   public static Iterator<String> of(final String value) {
  14.     final List<String> lines = ImmutableList.copyOf(value.split("\n"));
  15.     return lines.iterator();
  16.   }
  17.  
  18.   public static Iterable<String> toIterable(final String value) {
  19.     return new Iterable<String>() {
  20.       @Override public Iterator<String> iterator() {
  21.         return of(value);
  22.       }
  23.     };
  24.   }
  25.  
  26.   public static Iterator<String> of(final StringBuilder value) {
  27.     return new Iterator<String>() {
  28.       boolean hasNext = true;
  29.       boolean removed = false;
  30.       int start = 0;
  31.       int end = -1;
  32.       @Override public boolean hasNext() {
  33.         return hasNext;
  34.       }
  35.  
  36.       @Override public String next() {
  37.         removed = false;
  38.         if (!hasNext) {
  39.           throw new NoSuchElementException();
  40.         }
  41.         start = end + 1;
  42.         end = value.indexOf("\n", start);
  43.         if (end == -1) {
  44.           hasNext = false;
  45.         }
  46.         return value.substring(
  47.             start,
  48.             end == -1 ? value.length() : end);
  49.       }
  50.  
  51.       @Override public void remove() {
  52.         if (removed) {
  53.           throw new IllegalStateException("Multiple calls to remove() without and intervening call to next().");
  54.         }
  55.         value.delete(
  56.             start,
  57.             end == -1 ? value.length() : end + 1);
  58.         end = start - 1;
  59.         removed = true;
  60.       }
  61.     };
  62.   }
  63.  
  64.   public static Iterable<String> toIterable(final StringBuilder value) {
  65.     return new Iterable<String>() {
  66.       @Override public Iterator<String> iterator() {
  67.         return of(value);
  68.       }
  69.     };
  70.   }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement