Streams
Divisible by 3
long numbersDivisibleByThree = inputs.stream()
.mapToInt(s -> Integer.valueOf(s))
.filter(number -> number % 3 == 0)
.count();
Divisible by 3
long numbersDivisibleByThree = inputs.stream()
.mapToInt(s -> Integer.valueOf(s))
.filter(number -> number % 3 == 0)
.count();
Average
double average = inputs.stream()
.mapToInt(s -> Integer.valueOf(s))
.average()
.getAsDouble();
Filter and create another list with filtered values
ArrayList<Integer> values = list.stream()
.filter(value -> value > 5)
.map(value -> value * 2)
.collect(Collectors.toCollection(ArrayList::new));
Print all values in collections
values.stream()
.filter(value -> value % 2 == 0)
.forEach(value -> System.out.println(value));
Filter by lastName in Alphabetical order
persons.stream()
.map(person -> person.getLastName())
.distinct()
.sorted()
.forEach(name -> System.out.println(name));
Convert while loop for printing all elements into stream()
public void printItems() {
// int indeksi = 0;
// while (indeksi < this.suitcases.size()) {
// this.suitcases.get(indeksi).printItems();
// indeksi++;
// }
this.suitcases.stream()
.forEach(suitcase -> suitcase.printItems());
}
Convert while loop to add all the weights of all elements in a list to a stream() ``` public int totalWeight() { int summa = 0; int indeksi = 0;
// while (indeksi < this.suitcases.size()) { // summa += this.suitcases.get(indeksi).totalWeight(); // indeksi++; // } return this.suitcases.stream() .mapToInt(Suitcase::totalWeight) .sum(); }
**Programm that creates objects with data from file and prints them**
public class BooksFromFile {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// test your method here
readBooks("books.txt").stream()
.forEach(System.out::println);
}
public static List<Book> readBooks(String file) {
List<Book> books = new ArrayList<>();
try {
Files.lines(Paths.get(file))
.map(row -> row.split(","))
.map(parts -> new Book(parts[0], Integer.valueOf(parts[1]), Integer.valueOf(parts[2]), parts[3]))
.forEach(books::add);
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
return books;
}
}
**Program that reads data from file, sorts it (alphabetically, by size, etc.) and prints it**
try { Files.lines(Paths.get(“literacy.csv”)) .map(x -> x.split(“,”)) .sorted((x, y) -> x[5].compareTo(y[5])) .forEach(row -> System.out.println(row[3] + ” (” + row[4] + “),” + row[2].split(” “)[1].trim() +”, ” + row[5])); } catch (IOException e) { System.out.println(“Error:” + e.getMessage()); }
**Sorting By Multiple Criteria**
We'll use Java's Comparator class with methods comparing and theComparing. Example <https://github.com/isaac-diez/java_mooc_2/blob/master/part10-Part10_14.Literature/src/main/java/MainProgram.java>
Comparator<Book> comparator = Comparator
.comparing(Book::getBookAgeRecommendation)
.thenComparing(Book::getBookName);
Collections.sort(books, comparator);
for (Book b : books) {
System.out.println(b);
}
```