gpt4 book ai didi

java - 将 ArrayList 中的相同项目分组 - MusicPlayer

转载 作者:行者123 更新时间:2023-12-01 12:03:51 25 4
gpt4 key购买 nike

我正在尝试将多个 ArrayList 组合起来作为音乐播放器。当前列表会生成每首歌曲的艺术家,而不仅仅是一位艺术家。希望这能更好地解释它:

Screenshot

我当前的一个 fragment 的代码是这样的:

public class ArtistsFragment extends Fragment {

private ArrayList<Artist> artistList;
View view;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

view = inflater.inflate(R.layout.fragment_artists, container, false);

GridView gvArtists = (GridView) view.findViewById(R.id.gvArtists);

//instantiate list
artistList = new ArrayList<>();

//get artists from device
getArtistList();

// Group ArrayList..
artistList = new ArrayList<>(new HashSet<>(artistList));

//sort alphabetically by title
Collections.sort(artistList, new Comparator<Artist>() {
public int compare(Artist a, Artist b) {
return a.getArtist().compareTo(b.getArtist());
}
}
);

//create and set adapter
ArtistAdapter artistAdt = new ArtistAdapter(getActivity(), artistList);
gvArtists.setAdapter(artistAdt);

return view;
}

void getArtistList() {
//retrieve artist info
ContentResolver musicResolver = getActivity().getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);

if (musicCursor != null && musicCursor.moveToFirst()) {
//get columns
int idColumn = musicCursor.getColumnIndex
(MediaStore.Audio.Media._ID);
int artistColumn = musicCursor.getColumnIndex
(MediaStore.Audio.Albums.ARTIST);
int artColumn = musicCursor.getColumnIndex
(MediaStore.Audio.Media.ARTIST_ID);

//add artists to list
do {
long thisId = musicCursor.getLong(idColumn);
String thisArtist = musicCursor.getString(artistColumn);
String thisArt = musicCursor.getString(artColumn);

artistList.add(new Artist(thisId, thisArtist, thisArt));
}
while (musicCursor.moveToNext());
musicCursor.close();
}
}

}

艺术家等级

class Artist {
private final long id;
private final String artist;
private final String art;

public Artist(long artistID, String theartist, String artistArt) {
id = artistID;
artist = theartist;
art = artistArt;
}

public long getID() {
return id;
}

public String getArtist() {
return artist;
}

public String getArt() {
return art;
}
}

我查看了Map,我查看了Set,现在我只是感到困惑......

那么,如何对 ArrayList 进行分组以删除不同艺术家的重复项,然后最终使用 OnPickedArrayList 更改为该组/类别中的那些分组歌曲?

我的思路是否正确,或者是否有完全不同的方法来对流派/艺术家/专辑等进行排序?

最佳答案

如果清除重复项是您唯一的问题,那么以下是如何清除列表中的所有重复项(将其转换为 Set 并返回):

Set<Artist> set = new HashSet<Artist>(artistList);
artistList = new ArrayList<Artist>(set);
//then sort it...

或一行

artistList = new ArrayList<Artist>(new HashSet<Artist>(artistList));

您还应该根据使列表中的条目唯一的字段重写 equals() 和 hashCode() 方法。

关于java - 将 ArrayList 中的相同项目分组 - MusicPlayer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27807660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com