Java Streams API

class Test { public static void main(String[] args) { List<String> names = new ArrayList<>(Arrays.asList(“Megan”, “John”, “Melissa”, “Tom”, “John”, “Megan”, “Steve”, “Tom”)); List<String> uniqueNames = names.stream() .distinct() .collect(Collectors.toList()); System.out.println(uniqueNames); } } Output: [Megan, John, Melissa, Tom, Steve] class User { private String name; private String username; private String membershipType; private String address; public User(String name, String…

Read More Streams – distinct() operation

Stream<T> filter(Predicate<? super T> predicate) class Test { public static void main(String[] args) { List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); List<Integer> filteredNumbers = numbers.stream() .filter(number -> number % 2 == 0) .collect(Collectors.toList()); System.out.println(filteredNumbers); } } Output: [2, 4, 6, 8, 10] class Student { private String firstName;…

Read More Streams – filter() operation

class Test { public static void main(String[] args) { List<String> cities = new ArrayList<>(Arrays.asList(“New York”, “Berlin”, “Bangkok”, “London”)); List<String> modifiedList = cities.stream() .map(String::toUpperCase) .collect(Collectors.toList()); modifiedList.forEach(System.out::println); } } Output: NEW YORK BERLIN BANGKOK LONDON List<List<String>> cities = new ArrayList<>(); cities.add(new ArrayList<>(Arrays.asList(“Paris”, “London”))); cities.add(new ArrayList<>(Arrays.asList(“New York”, “Berlin”))); class Test { public static void main(String[] args) { List<List<String>>…

Read More Streams – flatMap() operation

class Test { public static void main(String[] args) { List<String> cities = new ArrayList<>(Arrays.asList(“New York”, “Paris”, “London”, “Monte Carlo”, “Berlin”)); cities.stream() .map(city -> city.toUpperCase()) .forEach(city -> System.out.println(city)); } } Output: NEW YORK PARIS LONDON MONTE CARLO BERLIN class Test { public static void main(String[] args) { List<String> cities = new ArrayList<>(Arrays.asList(“New York”, “Paris”, “London”, “Monte…

Read More Streams – map() operation