Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import java.util.stream.IntStream;
- class Song {
- private String title;
- private String[] artists;
- public Song(String title, String[] artists) {
- this.title = title;
- this.artists = artists;
- }
- @Override
- public String toString() {
- return "Song{" +
- "title='" + title + '\'' +
- ", artists=" + Arrays.toString(artists) +
- '}';
- }
- public void play() {
- System.out.println("Play " + this.toString());
- }
- public String getTitle() {
- return title;
- }
- }
- class MusicLib {
- private List<Song> songs;
- public MusicLib() {
- this.songs = new ArrayList<>();
- }
- public void addSong(final Song song) {
- songs.add(song);
- }
- public void rmSong(int index) {
- songs.remove(index);
- }
- public List<Song> getSongs() {
- return songs;
- }
- public void playByTitle(final String title) {
- IntStream intStream = IntStream.range(0, songs.size());
- OptionalInt index = intStream.filter(i -> songs.get(i).getTitle().equals(title)).findFirst();
- songs.get(index.getAsInt()).play();
- }
- public void playRandom() {
- final int size = songs.size();
- if (size == 0) {
- return;
- }
- var random = new Random();
- int index = random.nextInt(size);
- songs.get(index).play();
- }
- }
- public class Main {
- public static void main(String[] args) {
- var musicLib = new MusicLib();
- musicLib.addSong(new Song("Midnight Train to Georgia", new String[]{"Gladys Knight & the Pips"}));
- musicLib.addSong(new Song("Stairway to Heaven", new String[]{"Led Zeppelin"}));
- musicLib.addSong(new Song("Imagine", new String[]{"John Lennon"}));
- musicLib.addSong(new Song("All by Myself", new String[]{"Eric Carmen"}));
- musicLib.addSong(new Song("What'd I Say", new String[]{"Ray Charles"}));
- musicLib.addSong(new Song("Walking in Memphis", new String[]{"Marc Cohn"}));
- musicLib.addSong(new Song("In the Air Tonight", new String[]{"Phil Collins"}));
- musicLib.playByTitle("Imagine");
- musicLib.playRandom();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement