Added hw3 sources

This commit is contained in:
Claudio Maggioni 2022-11-06 17:00:55 +01:00
parent 2940fa290c
commit 6e521f8226
8 changed files with 533 additions and 0 deletions

BIN
hw2/Claudio.Maggioni.zip Normal file

Binary file not shown.

BIN
hw2/Federico.Lagrasta.zip Normal file

Binary file not shown.

17
hw3/code/pom.xml Normal file
View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>Assignment3</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

View File

@ -0,0 +1,69 @@
package ch.usi.inf.ajp22;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
public class Album {
private List<Track> tracks;
private Artist artist;
private String title;
private static Comparator<Track> byDuration;
public Album(List<Track> songs, Artist artist, String title) {
this.tracks = songs;
this.artist = artist;
this.title = title;
}
public List<Track> getTracks() {
return tracks;
}
public void setTracks(List<Track> tracks) {
this.tracks = tracks;
}
public Artist getArtist() {
return artist;
}
public void setArtist(Artist artist) {
this.artist = artist;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
/**
* 3 Points
* TODO: create a public Optional<Track> method called "searchLongestSong" that
* return the longest Track in the album.
* input: void
* output: an Optional<Track>
*/
/**
* 3 Points
* TODO: create a public List<Track> method called "orderSongByTitle" that
* return the track list ordered lexicographically using the title field.
* input: void
* output: a List<Track>
*/
@Override
public String toString() {
return "ch.usi.inf.ajp22.Album{" +
"tracks=" + tracks +
", artist='" + artist.getName() + '\'' +
", title='" + title + '\'' +
'}';
}
}

View File

@ -0,0 +1,33 @@
package ch.usi.inf.ajp22;
public class Artist {
private String name;
private String nickname;
public Artist(String name) {
this.name = name;
this.nickname = "unknown";
}
public Artist(String name, String nickname) {
this.name = name;
this.nickname = nickname;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
}

View File

@ -0,0 +1,260 @@
package ch.usi.inf.ajp22;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDate;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.BinaryOperator;
import java.util.function.IntFunction;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
/**
* 3 Points
* TODO: create a public static Album method called "longestTitle".
* If the maximum is not found throw a RuntimeException.
* input: a list of Album
* output: the Album with the longest title.
*/
/**
* 4 Points
* TODO: create a public static int method called "sumOfRatingReduce".
* input: an Album instance.
* output: int that is the sum of all the tracks ratings in the album.
* Use the method getTracks from the Album class to get the List of tracks.
* You MUST use the reduce method, in the variant which takes as input an identity, an accumulator and a combiner.
* If possible use method references.
*/
/**
* 4 Points
* TODO: create a public static int method called "sumOfRatingCollection".
* input: an Album instance.
* output: int that is the sum of all the tracks ratings in the album
* Use the method getTracks from the Album class to get the List of tracks.
* You MUST use one variant of the collect method. If possible use method references.
*/
/**
* 4 Points
* TODO: create a public static int method called "sumOfRatingMap"
* input: an ch.usi.inf.ajp22.Album instance.
* output: int that is the sum of all the tracks ratings in the album.
* Use the method getTracks from the Album class to get the List of tracks.
* You MUST use the mapToInt method. If possible use method references.
*/
/**
* 4 Points
* TODO: create a public static Map<String, Long> method called "countTrackOccurrence"
* input: a list of Track
* output: a Map<String, Long> where the key is the track title and the value is, how many times
* the same song occurs in the list.
* Two songs can be considered the same if they have the same title.
*/
/**
* 4 Points
* TODO: create a public static Map<Artist, List<Album>> method called "groupAlbumByArtist".
* input: a list of Album
* output: a Map<Artist, List<Album>> where the key is an Artist and the value is a List of Album which
* this artist had produced.
*/
/**
* 4 Points
* TODO: create a public static List<Track> method called "trackFilteredWithPredicate".
* input: a stream of tracks and a predicate to apply to the track stream.
* output: a List of Track that has been filtered according to the predicate taken as input.
*/
/**
* 5 Points
* TODO: create a public static Stream<Album> method called getAlbumWithAtLeastNTracks
* input: a list of Album AND an int called "n"
* output: a List<Album> where every album in this stream has at least "n" tracks.
*/
/**
* 5 Points
* TODO: create a public static void method called "printTrackStatistics".
* input: an Album instance
* Print Track Statistics based on the length of the tracks of an album taken as input in the following format:
* ===
* "Stat for: %s\n", album.getTitle())
* "Max: %d\nMin: %d\nAve: %f\n"
* ===
* Use the method getTracks from the Album class to get the List of tracks.
* Input: an Album
*/
/**
* 5 Points
* TODO: create a public static String method called "getArtistNameAndNickNameFromAlbum".
* Each author should appear only once.
* input: a list of Album
* output: a String in the following format:
* [artist1.name - artist1.nickname, artist2.name - artist2.nickname, ...]
*/
/**
* 5 Points
* TODO: create a public Track method called "combineAllTrackInAlbum"
* input: a stream of track
* output: return a new ch.usi.inf.ajp22.Track with the following values:
* title -> "fake title"
* releaseDate -> LocaleDate.now()
* genre -> DISCO
* length -> the sum of all the lengths in the input track stream.
* The pipeline processing must be done in parallel.
* You MUST use the collect method, in the variant which takes as input a supplier, an accumulator and a
* combiner.
*/
/**
* 5 Points
* TODO: create a public static Map<Artist, List<Track>> method called "groupTrackByArtist".
* input: a list of Album
* output: a Map<Artist, List<Track>> where the key is an Artist and the value is a List of Track which
* this artist had produced.
*/
/**
* 5 Bonus Points
* TODO: create a public static <T> T[] method called "createArray".
* This method must create a generic array where the elements are in the same order as in the
* input Collection.
* In this function you need neither streams nor lambda.
* input: a Collection<T> and an IntFunction<T[]>
* output: an array of generic type
*/
private static void writeToFile(String s) throws IOException {
BufferedWriter fw = new BufferedWriter(new FileWriter("artist.txt", true));
fw.write(s);
fw.close();
}
public static void main(String[] args) {
Random random = new Random();
/**
* Initializing some SampleData
*/
SampleData.appetiteForDestruction
.getTracks().forEach(track ->
track.setRating(random.nextInt(5)));
SampleData.randomAccessMemories
.getTracks().forEach(track ->
track.setRating(random.nextInt(5)));
/**
* 2 Points
* TODO: Replace the Anonymous class below with a lambda expression.
*/
BinaryOperator<Track> mixTrack = new BinaryOperator<>() {
@Override
public Track apply(Track t1, Track t2) {
return new Track(t1.getTitle(),
t1.getReleasedDate(),
t2.getGenre(),
t2.getLength());
}
};
/**
* 3 Points
* TODO: Create a stream pipeline that:
* 1) filter all the tracks that have at least 4 as rating
* 2) sort the filtered tracks using the title field
* 3) print the tracks
*/
/**
* 4 Points
* TODO: Print on file the artist's name, obtained with the method SampleData.getArtistList(),
* using the writeToFile method. Use a lambda expression and handle
* the throw exception from the writeToFile method. If there is an IOException you must throw a
* RuntimeException with the same event.
*/
System.out.printf("Longest track in %s is %s\n",
SampleData.appetiteForDestruction.getTitle(),
SampleData.appetiteForDestruction.searchLongestSong().isPresent() ?
SampleData.appetiteForDestruction.searchLongestSong().get().getTitle() :
"Not found");
System.out.printf("Ordered song in %s\n",
SampleData.appetiteForDestruction.getTitle());
SampleData.appetiteForDestruction.orderSongByTitle()
.forEach(System.out::println);
printTrackStatistics(SampleData.appetiteForDestruction);
printTrackStatistics(SampleData.randomAccessMemories);
SampleData.appetiteForDestruction
.getTracks().forEach(System.out::println);
System.out.print("Tot rating for:\n" + SampleData.appetiteForDestruction.getTitle());
System.out.printf("\ttot rating (Reduce): %d\n", sumOfRatingReduce(SampleData.appetiteForDestruction));
System.out.printf("\ttot rating (Collection): %d\n", sumOfRatingCollection(SampleData.appetiteForDestruction));
System.out.printf("\ttot rating (mapToInt): %d\n", sumOfRatingMap(SampleData.appetiteForDestruction));
System.out.println("Tot occurrence in the following list are\n");
SampleData.getRepeatedTrack()
.forEach(System.out::println);
Map<String, Long> titleOccurrence = countTrackOccurrence(SampleData.getRepeatedTrack());
for (Map.Entry<String, Long> entry : titleOccurrence.entrySet()) {
System.out.printf("Title: %s occurrence: %d\n",
entry.getKey(), entry.getValue());
}
Map<Artist, List<Album>> artistListMap = groupAlbumByArtist(SampleData.getAlbumList());
for (Map.Entry<Artist, List<Album>> entry : artistListMap.entrySet()) {
System.out.println("ch.usi.inf.ajp22.Artist: " + entry.getKey().getName());
for (Album album : entry.getValue()) {
System.out.println("\t" + album.getTitle());
}
}
Map<Artist, List<Track>> artistListMap1 = groupTrackByArtist(SampleData.getAlbumList());
for (Map.Entry<Artist, List<Track>> entry : artistListMap1.entrySet()) {
System.out.println("ch.usi.inf.ajp22.Artist: " + entry.getKey().getName());
for (Track track: entry.getValue()) {
System.out.println("\t" + track.toString());
}
}
List<Track> trackPOPinGuns = trackFilteredWithPredicate(SampleData.appetiteForDestruction.getTracks().stream()
,(t -> !t.getGenre().equals(Track.Genre.HIP_HOP)));
trackPOPinGuns
.forEach(System.out::println);
getAlbumWithAtLeastNTracks(SampleData.getAlbumList(), 3)
.forEach(System.out::println);
System.out.println("Getting artist name " + getArtistNameAndNickNameFromAlbum(SampleData.getAlbumList()));
System.out.println("ch.usi.inf.ajp22.Album with the longest name is " + longestTitle(SampleData.getAlbumList()));
Album[] albumsArray = createArray(SampleData.getAlbumList(), Album[]::new);
System.out.println("ch.usi.inf.ajp22.Album array");
for (int i = 0; i < albumsArray.length; i++) {
System.out.println(albumsArray[i]);
}
Track combinedTrack = combineAllTrackInAlbum(SampleData.appetiteForDestruction.getTracks().stream());
System.out.println(combinedTrack);
}
}

View File

@ -0,0 +1,78 @@
package ch.usi.inf.ajp22;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
public class SampleData {
/*
* Guns N Roses - Appetite for destruction
*/
private static Artist gunsNroses = new Artist("Guns N' Roses", "G N' R");
private static Track welcomeToTheJungle = new Track("Welcome to the Jungle",
LocalDate.of(1987, 9, 28),
Track.Genre.ROCK, 273);
private static Track nighTrain = new Track("Nigh train",
LocalDate.of(1989, 6, 25),
Track.Genre.ROCK, 268);
private static Track mrBrownstone = new Track("Mr. Brownstone",
LocalDate.of(1987, 6, 15),
Track.Genre.ROCK, 229);
public static Album appetiteForDestruction = new Album(Arrays.asList(welcomeToTheJungle, nighTrain, mrBrownstone),
gunsNroses,
"Appetite for Destruction");
private static Artist daftPunk = new Artist("Daft Punk");
private static Track giveLifeBackToMusic = new Track("Give Life Back to Music",
LocalDate.of(2014, 1, 31),
Track.Genre.DISCO, 273);
private static Track instantCrush = new Track("Instant Crush",
LocalDate.of(2013, 11, 22),
Track.Genre.DISCO, 387);
private static Track getLucky = new Track("Get Lucky",
LocalDate.of(2013, 4, 19),
Track.Genre.DISCO, 247);
public static Track oneMoreTime = new Track("One More Time",
LocalDate.of(2000, 11, 13),
Track.Genre.DISCO, 321);
public static Track crescenDolls = new Track("Crescendolls",
LocalDate.of(2001, 3, 13),
Track.Genre.DISCO, 208);
public static Album randomAccessMemories = new Album(Arrays.asList(giveLifeBackToMusic,
instantCrush, getLucky), daftPunk, "Random Access Memories");
public static Album discovery = new Album(Arrays.asList(oneMoreTime, crescenDolls), daftPunk, "Discovery");
private static final List<Track> shuffledTrack = Arrays.asList(giveLifeBackToMusic, getLucky,
mrBrownstone, welcomeToTheJungle, instantCrush, nighTrain);
private static List<Album> albumList = Arrays.asList(randomAccessMemories, appetiteForDestruction, discovery);
private static List<Artist> artistList = Arrays.asList(daftPunk, gunsNroses);
private static List<Track> repeatedTrack = Arrays.asList(welcomeToTheJungle, welcomeToTheJungle,
nighTrain, instantCrush, instantCrush);
public static List<Artist> getArtistList() {
return artistList;
}
public static List<Album> getAlbumList() {
return albumList;
}
public static List<Track> getShuffledTrack() {
return shuffledTrack;
}
public static List<Track> getRepeatedTrack() {
return repeatedTrack;
}
}

View File

@ -0,0 +1,76 @@
package ch.usi.inf.ajp22;
import java.time.LocalDate;
public class Track {
public enum Genre {
ROCK, METAL, DISCO, HIP_HOP, INDIE
}
private String title;
private LocalDate releasedDate;
private Genre genre;
private int length;
private int rating;
public Track(String title, LocalDate releasedDate, Genre genre, int length) {
this.title = title;
this.releasedDate = releasedDate;
this.genre = genre;
this.length = length;
}
public Track(String title, LocalDate releasedDate) {
this.title = title;
this.releasedDate = releasedDate;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public LocalDate getReleasedDate() {
return releasedDate;
}
public void setReleasedDate(LocalDate releasedDate) {
this.releasedDate = releasedDate;
}
public Genre getGenre() {
return genre;
}
public void setGenre(Genre genre) {
this.genre = genre;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
@Override
public String toString() {
return "Title: " + this.getTitle() + " Genre: " + this.genre.toString()
+ " Rate: " + this.getRating() + " Length: " +
this.getLength();
}
}