Skip to content

Instantly share code, notes, and snippets.

@cr0wst
Created June 17, 2018 14:33
Show Gist options
  • Save cr0wst/9bf4dc0ae5df0f1ec8a4100382f610a1 to your computer and use it in GitHub Desktop.
Save cr0wst/9bf4dc0ae5df0f1ec8a4100382f610a1 to your computer and use it in GitHub Desktop.
Java Stream Example: Iterate through list and display all others for each element.
package net.smcrow.sandbox.streams;
import java.util.List;
public class AllExceptCurrent {
private static final List<String> FRIENDS = List.of("Sarah", "John", "Megan", "Joseph");
public static void main(String... args) {
System.out.println("Without Streams");
withoutStreams();
System.out.println("With Streams");
withStreams();
}
private static void withoutStreams() {
for (String friend : FRIENDS) {
System.out.println("Friends of " + friend + ":");
for (String other : FRIENDS) {
if (!friend.equals(other)) {
System.out.println(other);
}
}
}
}
private static void withStreams() {
FRIENDS.forEach(friend -> {
System.out.println("Friends of " + friend + ":");
FRIENDS.stream().filter(other -> !friend.equals(other)).forEach(System.out::println);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment