Java 19.11.2023

This commit is contained in:
StNicolay 2023-11-19 17:57:27 +00:00
parent b206984ac9
commit fe789b95e4

View File

@ -855,20 +855,99 @@ class Main {
## Comparator & Comparable
```Java
import java.util.Comparator;
import java.util.TreeSet;
class Person implements Comparable<Person> {
private String name;
private int age;
Person(String name) {
Person(String name, int age) {
this.name = name;
this.age = age;
}
String getName() {
return name;
}
int getAge() {
return age;
}
// Отриц число, если меньше, 0, если равно, и полож число, если больше
public int compareTo(Person p) {
return name.compareTo(p.getName());
}
}
class PersonNameComparator implements Comparator<Person> {
public int compare(Person a, Person b) {
return a.getName().compareTo(b.getName());
}
}
class PersonAgeComparator implements Comparator<Person> {
public int compare(Person a, Person b) {
return a.getAge() - b.getAge();
}
}
class Main {
public static void Main(String[] args) {
Comparator<Person> pcomp = (new PersonNameComparator()).thenComparing(new PersonAgeComparator());
TreeSet<Person> people = new TreeSet<Person>(pcomp);
people.add(new Person("Tom", 10));
people.add(new Person("Tam", 12));
people.add(new Person("Tim", 13));
people.add(new Person("Bill", 40));
people.add(new Person("Bob", 15));
for(Person p : people) {
System.out.println(p.getName());
}
}
}
```
## Лямбда
> Лямбда представляет набор инструкций,которые можно выделить в отдельную переменную
```Java
public class Main {
public static void Main(String[] args) {
Operation op = (x, y) -> x + y;
Operation op2 = (int x, int y) -> x - y;
int result = op.calculate(10, 20);
System.out.println(result);
System.out.println(op.calculate(10, 20));
}
}
interface Operation {
int calculate(int x, int y);
}
```
Альтернативные формы:
* () -> 30 + 30
* n -> n * n
Лямбда функции могут возвращать void
```Java
interface Printer {
void print(String s);
}
class Main {
public static void Main(String[] args) {
Printer p = (s) -> System.out.println(s);
}
}
```
Переменные, которые используются в лямбде нельзя менять