Created
March 3, 2017 05:56
-
-
Save dpyro/07a04502e8cad4a044356f321f355019 to your computer and use it in GitHub Desktop.
return a random subset of a given stream
This file contains hidden or 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.util.List; | |
import java.util.Random; | |
import java.util.stream.Collectors; | |
import java.util.stream.Stream; | |
import java.util.Arrays; | |
public class RandomSubset { | |
// Returns a random subset of a given stream. | |
static <E> List<E> getRandomSubset(Stream<E> stream) { | |
Random rand = new Random(); | |
return stream | |
.filter(o -> { return rand.nextBoolean(); }) | |
.collect(Collectors.toList()); | |
} | |
public static void main(String[] args) { | |
if (args.length == 0) { | |
System.err.println("Usage: java RandomSubset StringElement [StringElement]+"); | |
System.exit(1); | |
} | |
Stream<String> stream = Arrays.stream(args); | |
List<String> result = getRandomSubset(stream); | |
String output = String.join(" ", result); | |
System.out.println(output); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment