Im trying to iterate a Linked List inside of a linked list but I’m not sure how to proceed with it. I’m used to using a passed parameter for what will be iterated but when I’m iterating a linked list within a linked list and plan to iterate until I hit a record that matches a passed dummy object.
Here is an example of what I’m trying to do
private static boolean addSongFromAlbumToAlbum(LinkedList<Album> albums1, LinkedList<Song> targetAlbum, String title){ //creating a dummy song for comparison of title parameter with arbitrary time duration. Song dummySong = new Song(title, 000); ListIterator<Album> album1ListIterator = albums1.listIterator(); ListIterator<Song> targetAlbumListIterator = targetAlbum.listIterator(); //nested album iterator ListIterator<Song> nestedAlbumInAlbum = nestedAlbum.listIterator(); //checking whether the song with the "title" parameter entered exists in the LinkedList //of albums while(album1ListIterator.hasNext()){ while(nestedAlbumInAlbum.hasNext()){ //checking if current iteration has an object with same value for title as title parameter. Song comparisonSongToAdd = nestedAlbumInAlbum.next(); int comparisonValue = comparisonSongToAdd.getTitle().compareTo(title); if(comparisonValue ==0){ //check whether the found object already exists in the album while (targetAlbumListIterator.hasNext()){ SongComparator comparator = new SongComparator(); //create new comparator object to compare int comparatorValue = comparator.compare(comparisonSongToAdd, targetAlbumListIterator.next()); if (comparatorValue == 0) { System.out.println(comparisonSongToAdd + " already exists in the Album. please choosen a different song."); return false; }//end if comparator }//end target album while targetAlbumListIterator.add(comparisonSongToAdd); }//end if song title found }//end nested album while }//end albums while iterator return true; }//end addSongFromAlbum method
///Here is the SongComparator class
public class SongComparator implements Comparator<Song> { public int compare(Song song1, Song song2){ if(song1.getTitle() == song2.getTitle() && song1.getDurationSeconds() == song2.getDurationSeconds()){ return 0; }else{ return -1; } } }
How am I supposed to iterate the LinkedList within the LinkedList of albums without a parameter? And if it requires a parameter how I’m I supposed to determine what to use for the parameter considering it will be changing with each iteration of the outer while loop.
Advertisement
Answer
you can use java 8 streams, instead of creating iterators,
in order to find whats in album 1 and album 2 use:
albums1.forEach(album1Element -> { //keeps only what returns true in the filter. List<Song> listOfSongsToAdd = targetAlbum.filter(song -> song.compareTo(title)).collect(Collectors.toList); listOfSongsToAdd.forEach(songToAdd -> { ... }); });