简体   繁体   English

将对象添加到ArrayLists的ArrayList

[英]Adding an object to an ArrayList of ArrayLists

I have an ArrayList of ArrayLists that hold MusicTrack objects. 我有一个ArrayList的ArrayLists,它包含MusicTrack对象。 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. 我很难将MusicTrack对象添加到这些内部ArrayLists中。

For example: titles[0] holds all tracks that start with A and so on through titles[26] holding Z tracks. 例如:titles [0]保存所有以A开头的曲目,依此类推,通过标题[26]保存Z曲目。 The MusicTrack object has a getter method called getTitle() to return the title string for comparison. MusicTrack对象有一个名为getTitle()的getter方法,用于返回标题字符串以进行比较。

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. 当我使用for循环时,它将每个轨道添加到每个单独的数组列表,所以我知道它是不正确的,但我不知道什么是正确的方法。

I would recommend using a Map instead of nested lists. 我建议使用Map而不是嵌套列表。 You can use Java Streams to achieve that: 您可以使用Java Streams来实现:

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: 如果您希望按键对地图进行排序,可以使用TreeMap

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() : 最后,如果您确实需要使用嵌套列表,还可以使用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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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