Java 8 Stream Examples
- rajasrikarraoj2ee
- Jan 18, 2021
- 1 min read
Updated: Feb 13, 2021
Below are list of Java Collection Stream API Usage Examples :
List<String> names = Arrays.asList("Apple", "Banana", "Mango", "Grapes", "Orange", "Apple", "PineApple", "WaterMelon", "Banana");
System.out.println(names.stream().filter( eachName -> eachName.length() > 0).collect(Collectors.toList()));
System.out.println(names.stream().filter( eachName -> eachName.length() > 0).sorted().collect(Collectors.toList()));
System.out.println(names.stream().distinct().filter( eachName -> eachName.length() > 0).collect(Collectors.toList()));
System.out.println(names.stream().filter( eachName -> eachName.length() > 0).collect(Collectors.toSet()));
System.out.println(names.stream().distinct().filter( eachName -> eachName.startsWith("A")).collect(Collectors.toSet()));
System.out.println(names.stream().distinct().filter( eachName -> eachName.startsWith("A")).skip(1).collect(Collectors.toSet()));
System.out.println(names.stream().peek(e -> e.toLowerCase()).collect(Collectors.toList()));
final AtomicInteger atomicInt = new AtomicInteger(0);
// Use Binary Func at the end to fix Duplicate key and throwing Illegal State
Map<Integer, String> mappedOut = names.stream().collect(Collectors.toMap( (eachStr) -> atomicInt.incrementAndGet(), Function.identity()));
System.out.println(mappedOut );
Komentar