Stream Übungen

master
3009594 2024-11-23 23:36:31 +01:00
parent c3387c13e6
commit 10f251b78b
8 changed files with 1644 additions and 0 deletions

View File

@ -0,0 +1,184 @@
package streams.übungen.Animal;
import java.util.*;
import java.util.stream.Collectors;
public abstract class Animal {
private int legs;
public Animal(int legs) {
this.legs = legs;
}
public int getLegs() {
return legs;
}
public void walk() {
System.out.println(
String.format("Animal with %d legs is walking now...",legs)
);
}
@Override
public String toString() {
return "Animal [legs=" + legs + "]";
}
public abstract void eat(); // abstract method
public static void main(String[] args) {
ArrayList<Animal> animals = new ArrayList<>();
// Katzen hinzufügen
animals.add(new Cat("Tom"));
animals.add(new Cat("Tom"));
animals.add(new Cat("Whiskers"));
animals.add(new Cat("Mittens"));
animals.add(new Cat("Felix"));
// Fische hinzufügen
animals.add(new Fish("Nemo"));
animals.add(new Fish("Dory"));
animals.add(new Fish("Bubbles"));
animals.add(new Fish("Goldie"));
animals.add(new Fish("Splash"));
// Spinnen hinzufügen
animals.add(new Spider());
animals.add(new Spider());
//animal with the highest number of legs
Animal a = animals.stream()
.max(Comparator.comparingInt(d -> d.getLegs()))
.orElse(null);
//Q.5) Find the total number of legs
int max = animals.stream()
.map(t -> t.getLegs())
.mapToInt(Integer::intValue)
.sum();
//Group the animals by their number of legs
Map<Animal, Long> animalMap = animals.stream()
.collect(Collectors.groupingBy(d -> d, Collectors.counting()));
animalMap.forEach((animal, count) ->
System.out.println(animal + " -> " + count + " mal"));
}
}
abstract interface Pet {
abstract void setName(String name);
public String getName();
abstract public void play();
static void playIfPet(Animal animal) {
if (animal instanceof Pet)
((Pet) animal).play();
}
}
class Cat extends Animal implements Pet {
private String name;
public Cat() {
this("Garfield");
}
public Cat(String name) {
super(4);
this.name = name;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public void play() {
System.out.println(String.format("%s is playing now...", name));
}
@Override
public void eat() {
System.out.println(String.format("%s is eating now...", name));
}
@Override
public String toString() {
return "Cat [name=" + name + "]";
}
}
class Fish extends Animal implements Pet {
private String name;
public Fish(String name) {
super(0);
this.name = name;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public void play() {
System.out.println(String.format("%s is playing now...", name));
}
@Override
public void eat() {
System.out.println(String.format("%s is eating now...", name));
}
@Override
public void walk() {
System.out.println(String.format("%s is swimming now...", name));
}
@Override
public String toString() {
return "Fish [name=" + name + "]";
}
}
class Spider extends Animal {
public Spider() {
super(8);
}
@Override
public void eat() {
System.out.println("Spider is eating now...");
}
@Override
public String toString() {
return "Spider [=" + getLegs() + ", toString()=" + super.toString()+ "]";
}
}

View File

@ -0,0 +1,40 @@
package streams.übungen;
public class City {
private int id;
private String name;
private Integer population;
private String countryCode;
public City() {
}
public City(int id, String name, String countryCode, Integer population) {
this.id = id;
this.name = name;
this.population = population;
this.countryCode = countryCode;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public Integer getPopulation() {
return population;
}
public String getCountryCode() {
return countryCode;
}
@Override
public String toString() {
return "City [id=" + id + ", name=" + name + ", population=" + population + ", countryCode=" + countryCode
+ "]";
};
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,92 @@
package streams.übungen;
import java.util.*;
public class Country {
private String code; // z. B. Länder-Code
private String name; // Name des Landes
private String kontinent; // Kontinent
private double flaeche; // Fläche
private int bevoelkerung; // Bevölkerung
private double bruttosozialprodukt; // BSP
private int hauptstadt; // Hauptstadt (ID oder Referenz)
private ArrayList<City> Cities; // Liste der Städte
public Country(String code, String name, String kontinent, int bevoelkerung,
double flaeche, double bruttosozialprodukt, int hauptstadt) {
this.Cities = new ArrayList<>();
this.code = code;
this.name = name;
this.kontinent = kontinent;
this.flaeche = flaeche;
this.bevoelkerung = bevoelkerung;
this.hauptstadt = hauptstadt;
this.bruttosozialprodukt = bruttosozialprodukt;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getKontinent() {
return kontinent;
}
public void setKontinent(String kontinent) {
this.kontinent = kontinent;
}
public double getFlaeche() {
return flaeche;
}
public void setFlaeche(double flaeche) {
this.flaeche = flaeche;
}
public double getBruttosozialprodukt() {
return bruttosozialprodukt;
}
public void setBruttosozialprodukt(double bruttosozialprodukt) {
this.bruttosozialprodukt = bruttosozialprodukt;
}
public int getHauptstadt() {
return hauptstadt;
}
public void setHauptstadt(int hauptstadt) {
this.hauptstadt = hauptstadt;
}
public void setBevoelkerung(int bevoelkerung) {
this.bevoelkerung = bevoelkerung;
}
public int getBevoelkerung() {
return bevoelkerung;
}
public ArrayList<City> getCities() {
return Cities;
}
@Override
public String toString() {
return "Land [ name=" + name + ", bevoelkerung=" + bevoelkerung + "]";
}
}

View File

@ -0,0 +1,51 @@
package streams.übungen;
import java.util.ArrayList;
public class CountryTest {
ArrayList<Country> test;
CountryTest(){
test = new ArrayList<>();
coutryTest();
}
public void coutryTest() {
// Erstelle Cities
City berlin = new City(1, "Berlin", "DE", 3769000);
City hamburg = new City(2, "Hamburg", "DE", 1845000);
City munich = new City(3, "Munich", "DE", 1472000);
City baden = new City(2, "Baden", "DE", 1845000222);
City paris = new City(4, "Paris", "FR", 2148000);
City lyon = new City(5, "Lyon", "FR", 515695);
City marseille = new City(6, "Marseille", "FR", 861635);
City tokyo = new City(7, "Tokyo", "JP", 13929000);
City osaka = new City(8, "Osaka", "JP", 2725000);
City kyoto = new City(9, "Kyoto", "JP", 1474570);
// Erstelle Countries
Country germany = new Country("DE", "Germany", "Europe", 83020000, 357022.0, 4.2, 1);
germany.getCities().add(berlin);
germany.getCities().add(hamburg);
germany.getCities().add(munich);
germany.getCities().add(baden);
Country france = new Country("FR", "France", "Europe", 67060000, 551695.0, 2.8, 4);
france.getCities().add(paris);
france.getCities().add(lyon);
france.getCities().add(marseille);
Country japan = new Country("JP", "Japan", "Asia", 125800000, 377975.0, 5.2, 7);
japan.getCities().add(tokyo);
japan.getCities().add(osaka);
japan.getCities().add(kyoto);
// Füge Countries zur Liste hinzu
test.add(germany);
test.add(france);
test.add(japan);
}
}

View File

@ -0,0 +1,138 @@
package streams.übungen;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
countryTest();
}
public static void countryTest() {
CountryTest test = new CountryTest();
//Q.2) Find the most populated city of each country
Map<Country,City> q2 = test.test
.stream()
.parallel()
.collect(Collectors.toMap(
country -> country,
country -> country.getCities().stream()
.max(Comparator.comparingInt(t -> t.getPopulation()))
.orElse(null)
));
// q2.forEach((a,b) -> System.out.println(a + " " + b));
//finde die Länder mit ihrer Städte.
Map<Country,List<City>> q6 = test.test
.stream()
.collect(Collectors.toMap(
country -> country,
country -> country.getCities().stream()
.collect(Collectors.toCollection(ArrayList::new))
));
//q6.forEach((a,b) -> System.out.println(a + " " + b.toString()));
// Durchschnitt jedes Land
Map<Country, Double> q5 = test.test.stream()
.collect(Collectors.toMap(
country -> country,
country -> country.getCities().stream()
.collect(Collectors.averagingDouble(e -> e.getPopulation()))));
//q5.forEach((a,b) -> System.out.println(a + " " + b));
//
// test.test.stream()
// .forEach(t -> {
// System.out.println(t.getName());
// t.getCities().stream()
// .forEach(f -> System.out.println("Stadt: " + f.getName()));
// });
// Paralleler Stream mit forEach (Reihenfolge nicht garantiert)
System.out.println("Paralleler Stream mit forEach:");
ArrayList<Integer> s1 = new ArrayList<>();
s1.add(1);
s1.add(5);
s1.add(4);
s1.add(2);
s1.parallelStream().sorted().forEach(System.out::println);
ArrayList<Integer> s4 = s1.stream().parallel().sorted().collect(Collectors.toCollection(ArrayList::new));
System.out.println(s4);
System.out.println("\nParalleler Stream mit forEachOrdered:");
// Paralleler Stream mit forEachOrdered (Reihenfolge garantiert)
ArrayList<Integer> s2 = new ArrayList<>();
s2.add(1);
s2.add(5);
s2.add(4);
s2.add(2);
s2.parallelStream().sorted().forEachOrdered(System.out::print);
}
public static void cityTest() {
CityTest test = new CityTest();
//Map<Integer, List<City>>
City x = test.cities.values()
.stream()
.max(Comparator.comparingInt(c -> c.getPopulation()))
.orElse(null);
System.out.println(x.toString());
Map<String, List<City>> nachCod = test.cities.values()
.stream()
.collect(Collectors.groupingBy(t -> t.getCountryCode(), Collectors.toCollection(ArrayList::new)));
nachCod.forEach((a,b) -> System.out.println("countryCode: " + a + " " + b));
}
public static void movieTest() {
MovieTest test = new MovieTest();
//
// Map<Director, Long> moviesPerDirector = test.movies.values().stream()
// .flatMap(movie -> movie.getDirectors().stream())
// .collect(Collectors.groupingBy(director -> director, Collectors.counting())); // Gruppieren und zählen
//
//
// moviesPerDirector.forEach((director, count) -> {
// System.out.println("Director: " + director.getName() + ", Movies: " + count);
// });
//
//
// Map<Genre,Long> anzahlGenresjedesFilm = test.movies.values().stream()
// .flatMap(movie -> movie.getGenres().stream())
// .collect(Collectors.groupingBy(g -> g , Collectors.counting()));
//
// anzahlGenresjedesFilm.forEach((genre, count) -> {
// System.out.println("Genre: " + genre.getName() + ", Movies: " + count);
// });
Map<Boolean, List<Movie>> movies = test.movies
.stream()
.collect(Collectors.partitioningBy(m -> m.getGenre().equalsIgnoreCase("Drama") || m.getGenre().equalsIgnoreCase("Komödie"), Collectors.toCollection(ArrayList::new)));
// List<Movie> ohne = movies.get(false);
// ohne.forEach(System.out::println);
// List<Movie> mit = movies.get(true);
// mit.forEach(System.out::println);
Map<Integer, List<Movie>> nachJahr = test.movies
.stream()
.collect(Collectors.groupingBy(m -> m.getYear(), Collectors.toCollection(ArrayList::new)));
nachJahr.forEach((a,b) -> System.out.println(a +" "+ b + "\n"));
}
}

View File

@ -0,0 +1,44 @@
package streams.übungen;
public class Movie {
private int id;
private String title;
private int year;
private String genre;
private String director;
public Movie(int id, String title, int year, String genre, String director) {
this.id = id;
this.title = title;
this.year = year;
this.genre = genre;
this.director = director;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public int getYear() {
return year;
}
public String getGenre() {
return genre;
}
public String getDirector() {
return director;
}
@Override
public String toString() {
return "Movie [id=" + id + ", title=" + title + ", year=" + year + ", genre=" + genre + ", director=" + director
+ "]";
}
}

View File

@ -0,0 +1,51 @@
package streams.übungen;
import java.util.*;
public class MovieTest {
ArrayList<Movie> movies;
public MovieTest() {
movies = new ArrayList<>();
populate();
}
public void populate() {
movies.add(new Movie(1, "500 Days Of Summer", 2009, "Romance", "Marc Webb"));
movies.add(new Movie(2, "Beyond a Reasonable Doubt", 2009, "Thriller", "Peter Hyams"));
movies.add(new Movie(3, "Gamer", 2009, "Action", "Mark Neveldine"));
movies.add(new Movie(4, "Cheri", 2009, "Drama", "Stephen Frears"));
movies.add(new Movie(5, "Dorian Gray", 2009, "Fantasy", "Oliver Parker"));
movies.add(new Movie(6, "Inglourious Basterds", 2009, "War", "Quentin Tarantino"));
movies.add(new Movie(7, "Invictus", 2009, "Biography", "Clint Eastwood"));
movies.add(new Movie(8, "Julie and Julia", 2009, "Drama", "Nora Ephron"));
movies.add(new Movie(9, "Los abrazos rotos", 2009, "Drama", "Pedro Almodovar"));
movies.add(new Movie(10, "Of Mice and Men", 1992, "Drama", "Gary Sinise"));
movies.add(new Movie(11, "Armored", 2009, "Thriller", "Nimród Antal"));
movies.add(new Movie(12, "Bornova Bornova", 2009, "Drama", "Inan Temelkuran"));
movies.add(new Movie(13, "Coco avant Chanel", 2009, "Biography", "Anne Fontaine"));
movies.add(new Movie(14, "Nefes: Vatan Sagolsun", 2009, "War", "Levent Semerci"));
movies.add(new Movie(15, "Up", 2009, "Animation", "Pete Docter"));
movies.add(new Movie(16, "Whiteout", 2009, "Thriller", "Dominic Sena"));
movies.add(new Movie(17, "The Time Travelers Wife", 2009, "Romance", "Robert Schwentke"));
movies.add(new Movie(18, "Whatever Works", 2009, "Comedy", "Woody Allen"));
movies.add(new Movie(19, "Anonyma - Eine Frau in Berlin", 2009, "Drama", "Max Färberböck"));
movies.add(new Movie(20, "Zombieland", 2009, "Comedy", "Ruben Fleischer"));
movies.add(new Movie(21, "Weather Girl", 2009, "Comedy", "Blayne Weaver"));
movies.add(new Movie(22, "Watchmen", 2009, "Action", "Zack Snyder"));
movies.add(new Movie(23, "Adam Resurrected", 2008, "Drama", "Paul Schrader"));
movies.add(new Movie(24, "Angels and Demons", 2009, "Mystery", "Ron Howard"));
movies.add(new Movie(25, "Away We Go", 2009, "Romance", "Sam Mendes"));
movies.add(new Movie(26, "Last Ride", 2009, "Drama", "Glendyn Ivin"));
movies.add(new Movie(27, "The Boys Are Back", 2009, "Drama", "Scott Hicks"));
movies.add(new Movie(28, "Nothing But the Truth", 2008, "Drama", "Rod Lurie"));
movies.add(new Movie(29, "100 Feet", 2008, "Horror", "Eric Red"));
movies.add(new Movie(30, "The Tournament", 2009, "Action", "Scott Mann"));
}
}