简体   繁体   中英

Adding an object to an ArrayList of ArrayLists

I have an ArrayList of ArrayLists that hold MusicTrack objects. I want to have an array list for each letter of the alphabet and then within those holds all of the tracks that start with that letter. I am having troubling adding the MusicTrack objects to these inner ArrayLists.

For example: titles[0] holds all tracks that start with A and so on through titles[26] holding Z tracks. The MusicTrack object has a getter method called getTitle() to return the title string for comparison.

import java.util.ArrayList;

public class TitleBucket implements BucketInterface{
    private ArrayList<ArrayList<MusicTrack>> titles;

    public TitleBucket(){
        this.titles = new ArrayList<ArrayList<MusicTrack>>(26);
        for (int i=0; i<26; i++){
            titles.add(new ArrayList<MusicTrack>());
        }
    }

    public void addItem(MusicTrack itemToAdd){
        int comp = Character.toUpperCase(itemToAdd.getTitle().charAt(0)) - 'A'; 
        // Unsure where to go from here. The above line
        // gets the index of the outer ArrayList but I 
        // don't know how to add it to that ArrayList only
    }
}

When I used a for loop it added every track to every single array list so I know it was incorrect, but I don't know what is the right way.

I would recommend using a Map instead of nested lists. You can use Java Streams to achieve that:

Map<Character, List<MusicTrack>> titles = tracks.stream()
        .collect(Collectors.groupingBy(track -> Character.toUpperCase(track.getTitle().charAt(0))));

If you want the map to be sorted by key you can use a TreeMap for that:

Map<Character, List<MusicTrack>> titles = tracks.stream()
        .collect(Collectors.groupingBy(track -> Character.toUpperCase(track.getTitle().charAt(0)), TreeMap::new, Collectors.toList()));

Finally if you really need to use nested lists you can also transform the map again using Map.values() :

List<List<MusicTrack>> titles = new ArrayList<>(tracks.stream()
        .collect(Collectors.groupingBy(track -> Character.toUpperCase(track.getTitle().charAt(0)), TreeMap::new, Collectors.toList()))
        .values());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM