Skip to content

Commit

Permalink
Add Lambdas & Stream API code snippets
Browse files Browse the repository at this point in the history
  • Loading branch information
100yo committed Nov 30, 2024
1 parent e2d1591 commit 0f4c678
Show file tree
Hide file tree
Showing 9 changed files with 548 additions and 0 deletions.
1 change: 1 addition & 0 deletions 08-lambdas-and-stream-api/snippets/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Ламбда изрази и Stream API
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package bg.sofia.uni.fmi.mjt;

import java.util.function.Function;
import java.util.function.IntConsumer;
import java.util.function.Supplier;

public class MethRefExample {

public MethRefExample() {
System.out.println("No arg constructor invoked");
}

public MethRefExample(String s) {
System.out.println("String arg constructor invoked with param " + s);
}

public static void fun() {
System.out.println("fun() invoked");
}

public static void fun(int i) {
System.out.println("fun(int) invoked with argument " + i);
}

public static void main(String[] args) {

// method reference to overloaded constructor
Function<String, MethRefExample> stringConstructorRef1 = MethRefExample::new;
Function<String, MethRefExample> stringConstructorRef2 = s -> new MethRefExample(s);
MethRefExample example1 = stringConstructorRef1.apply("FMI");
MethRefExample example2 = stringConstructorRef1.apply("Rulez");

Supplier<MethRefExample> defaultConstructorRef = MethRefExample::new;
MethRefExample example3 = defaultConstructorRef.get();

// method reference to overloaded methods
IntConsumer methRef1 = MethRefExample::fun;
methRef1.accept(5);

NoArgNoReturn methRef2 = MethRefExample::fun;
methRef2.accept();

}

@FunctionalInterface
interface NoArgNoReturn {
void accept();
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package bg.sofia.uni.fmi.mjt.employees;

import java.util.Objects;

public class Employee {

private int id;
private String name;
private int age;
private double salary;
private double bonus;

public Employee(int id, String name, int age, double salary, double bonus) {
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
this.bonus = bonus;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public double getSalary() {
return salary;
}

public void setSalary(double salary) {
this.salary = salary;
}

public double getBonus() {
return bonus;
}

public void setBonus(double bonus) {
this.bonus = bonus;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
return id == employee.id;
}

@Override
public int hashCode() {
return Objects.hash(id);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package bg.sofia.uni.fmi.mjt.employees;

import java.util.List;

public class EmployeesExample {

public static void main(String... args) {
Employee e1 = new Employee(1, "Бай Кольо", 56, 1200.00, 340.00);
Employee e2 = new Employee(2, "Шефа", 43, 15000.00, 30000.00);
Employee e3 = new Employee(3, "Стажанта", 20, 850.00, 0.00);

List<Employee> employees = List.of(e1, e2, e3);

System.out.println(getEmployeeSalariesTotal(employees));
}

public static double getEmployeeSalariesTotal(List<Employee> employees) {
// Stream<T> -> reduce -> V
//
// initial value (identity): the initial value of the reduction and the default result if the stream is empty
// accumulator: This is a BinaryOperator function that takes two parameters:
// a partial result of the reduction operation and the next element of the stream
// combiner: combine the results of the accumulator function when processing elements in parallel
// The combiner is necessary in parallel operations, where the input stream is divided into
// multiple sub-streams that are processed independently and then the partial results
// are combined into a final result.
return employees.parallelStream()
.reduce(
0.0, // initial value
(res, el) -> res + el.getSalary(), // accumulator
(left, right) -> left + right); // combiner
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package bg.sofia.uni.fmi.mjt.gatherers;

import java.util.List;
import java.util.stream.Gatherers;
import java.util.stream.Stream;

public class GatherersExample {

// Stream Gatherers is a Java 22 & 23 preview feature
// They allow writing custom intermediate operations

public static void main(String[] args) {

// Fold example: factorial
// Similar to the terminal "reduce" but returns a stream of its single-element result
Stream.of(1, 2, 3, 4, 5) // ⟵ Source
.gather(Gatherers.fold(() -> 1, (a, b) -> a * b)) // ⟵ Intermediate operation
.forEach(System.out::println); // ⟵ Terminal operation

var words = List.of("the", "be", "two", "of", "and", "a", "in", "that");
System.out.println(words);

// Fixed window example
var wordGroupsFixed = words.stream() // ⟵ Source
.gather(Gatherers.windowFixed(3)) // ⟵ Intermediate operation
.toList(); // ⟵ Terminal operation
System.out.println(wordGroupsFixed);

// Sliding window example
var wordGroupsSliding = words.stream() // ⟵ Source
.gather(Gatherers.windowSliding(3)) // ⟵ Intermediate operation
.toList(); // ⟵ Terminal operation
System.out.println(wordGroupsSliding);

// Map concurrent example: leveraging virtual threads
Stream.of(1, 2, 3, 4, 5)
.gather(Gatherers.mapConcurrent(4, a -> a * 2))
.forEach(System.out::println);

}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package bg.sofia.uni.fmi.mjt.ints;

import java.util.Set;

public class IntsSum {

public static void main(String... args) {
Set<Integer> numbers = Set.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

int sumOf5 = numbers
.stream()
.limit(5)
.mapToInt(Integer::intValue)
.sum();

System.out.println(sumOf5); // what will be the result?
}

}
Loading

0 comments on commit 0f4c678

Please sign in to comment.