Last active
February 3, 2018 03:58
-
-
Save ntxinh/aed6751b62f5b9912b588aacb3262776 to your computer and use it in GitHub Desktop.
Java 8 - Stream
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
// filter(), findAny() and orElse() | |
Item item = items.stream() | |
.filter(item -> Objects.equals(item.getId(), itemId)) | |
.findAny() | |
.orElse(null); | |
// findFirst | |
Optional<Item> itemOpt = items.stream() | |
.filter(item -> Objects.equals(item.getId(), itemId)) | |
.findFirst(); | |
if(itemOpt.isPresent()) | |
Item item = itemOpt.get(); | |
// filter() and collect() | |
List<Item> items = items.stream() | |
.filter(item -> Objects.equals(item.getId(), itemId)) | |
.collect(Collectors.toList()); | |
// filter() and map() | |
String name = persons.stream() | |
.filter(x -> "jack".equals(x.getName())) | |
.map(Person::getName) //convert stream to String | |
.findAny() | |
.orElse(""); | |
List<String> collect = persons.stream() | |
.map(Person::getName) | |
.collect(Collectors.toList()); | |
// Array to Stream | |
//Arrays.stream | |
String[] array = {"a", "b", "c", "d", "e"}; | |
Stream<String> stream1 = Arrays.stream(array); | |
stream1.forEach(x -> System.out.println(x)); | |
//Stream.of | |
Stream<String> stream2 = Stream.of(array); | |
stream2.forEach(x -> System.out.println(x)); | |
// Primitive Arrays | |
// 1. Arrays.stream -> IntStream | |
int[] intArray = {1, 2, 3, 4, 5}; | |
IntStream intStream1 = Arrays.stream(intArray); | |
intStream1.forEach(x -> System.out.println(x)); | |
// 2. Stream.of -> Stream<int[]> | |
Stream<int[]> temp = Stream.of(intArray); | |
// Cant print Stream<int[]> directly, convert / flat it to IntStream | |
IntStream intStream2 = temp.flatMapToInt(x -> Arrays.stream(x)); | |
intStream2.forEach(x -> System.out.println(x)); | |
// allMatch(), anyMatch(), noneMatch() |
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
List<Long> ids = interviewSchedulings.stream().map(InterviewScheduling::getId).collect(Collectors.toList()); | |
Long[] ids = interviewSchedulings.stream().map(InterviewScheduling::getId).toArray(Long[]::new) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment