Skip to content

Instantly share code, notes, and snippets.

@bassemZohdy
Last active August 29, 2015 14:21
Show Gist options
  • Save bassemZohdy/34706a4bacd3e0e3db1e to your computer and use it in GitHub Desktop.
Save bassemZohdy/34706a4bacd3e0e3db1e to your computer and use it in GitHub Desktop.
import java.util.Iterator;
public class LineSplitter implements Iterable<String> {
private final String line;
private final char delimiter;
public LineSplitter(String line, char delimiter) {
this.line = line;
this.delimiter = delimiter;
}
@Override
public Iterator<String> iterator() {
return new Iterator<String>() {
private int index = 0;
private int to = 0;
@Override
public String next() {
if (!(to == line.length()))
to = line.indexOf(delimiter, index);
String s = line.substring(index, to);
index = to + 1;
return s;
}
@Override
public boolean hasNext() {
boolean b = line.length() == to;
if (to == line.lastIndexOf(delimiter))
to = line.length();
return !b;
}
};
}
}
import java.util.Iterator;
import java.util.NoSuchElementException;
public class LineSplitterByChar implements Iterable<String> {
private final String line;
private final char delimiter;
public LineSplitterByChar(String line, char delimiter) {
this.line = line;
this.delimiter = delimiter;
}
@Override
public Iterator<String> iterator() {
return new Iterator<String>() {
private int index = 0;
private final StringBuilder sb = new StringBuilder();
@Override
public String next() {
if (!hasNext())
throw new NoSuchElementException();
sb.setLength(0);
while (index < line.length() && line.charAt(index) != delimiter) {
sb.append(line.charAt(index));
index++;
}
index++;
return sb.toString();
}
@Override
public boolean hasNext() {
return (index < line.length());
}
};
}
}
import java.util.Iterator;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
public class LineSplitterByFuture implements Iterable<String> {
private final String line;
private final char delimiter;
public LineSplitterByFuture(String line, char delimiter) {
this.line = line;
this.delimiter = delimiter;
}
@Override
public Iterator<String> iterator() {
return new Iterator<String>() {
private int index = 0;
private int to = 0;
private Future<String> futureValue;
@Override
public String next() {
if (this.futureValue == null) {
return get();
}
String value = null;
try {
value = this.futureValue.get();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
this.futureValue = CompletableFuture.supplyAsync(this::get);
return value;
}
private String get() {
if (to == line.lastIndexOf(delimiter))
to = line.length();
else
to = line.indexOf(delimiter, index);
String temp = line.substring(index, to);
index = to + 1;
return temp;
}
@Override
public boolean hasNext() {
boolean b = line.length() == to;
if (to == line.lastIndexOf(delimiter))
to = line.length();
return !b;
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment