Last active
January 25, 2019 03:17
-
-
Save kamatama41/c9df528dc38d00636584424b70c2c336 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.BufferedReader; | |
import java.io.ByteArrayInputStream; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.io.InputStreamReader; | |
import java.nio.charset.StandardCharsets; | |
import java.util.Spliterator; | |
import java.util.stream.Stream; | |
public class ByteArrayStreamInputStream extends InputStream { | |
ByteArrayStreamInputStream(Stream<byte[]> source) { | |
this.source = source; | |
this.spliterator = source.spliterator(); | |
getNext(); | |
} | |
@Override | |
public int read() { | |
if (currentInputStream == null) { | |
return -1; // when source stream would be empty. | |
} | |
final int ret = currentInputStream.read(); | |
if (ret == -1) { | |
if (getNext()) { | |
// Read next bytes if exists | |
return read(); | |
} | |
return -1; | |
} | |
return ret; | |
} | |
@Override | |
public void close() { | |
source.close(); | |
} | |
private boolean getNext() { | |
return spliterator.tryAdvance(bytes -> currentInputStream = new ByteArrayInputStream(bytes)); | |
} | |
private final java.util.stream.Stream<byte[]> source; | |
private final Spliterator<byte[]> spliterator; | |
private ByteArrayInputStream currentInputStream; | |
public static void main(String[] args) throws IOException { | |
final Stream<String> filteredStrings = Stream.of("AA", "BB", "CC") | |
.filter(str -> !str.contains("B")) | |
.map(str -> str + System.getProperty("line.separator")); | |
InputStream input = new ByteArrayStreamInputStream(filteredStrings.map(str -> str.getBytes(StandardCharsets.UTF_8))); | |
try(BufferedReader reader = new BufferedReader(new InputStreamReader(input))) { | |
reader.lines().forEach(System.out::println); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment