我有一個來自網路服務的電影串列,我需要使用資料中的流派屬性來分組。我的問題與這個groupby ngFor angular2非常相似,但卻是在java中。
來自網路服務的電影串列看起來是這樣的
[
{
"title"。"AAAAAAA"。
"genres": [
"喜劇".
]
},
{
"標題": "BBBBBBBBBB",
"genres": [
"動作", "冒險"。
]
},
{
"title": "CCCCCCCC",
"genres": [
"Action", "genres".
]
},
{
"標題": "DDDDDDDDD",
"genres": [
"喜劇", "冒險"。
]
},
{
"標題": "EEEEEEEEEEEEEE",
"genres": [
"Horror".
]
}
]
這是我想實作的目標,但我似乎無法實作它
。[
{
"Action": [
{
"title": "BBBBBBBBBB"。
"genres": [
"動作", "冒險"。
]
},
{
"title": "CCCCCCCC",
"genres": [
"Action", "genres".
]
}
],
"冒險": [
{
"title": "BBBBBBBBBB",
"genres": [
"動作", "冒險"。
]
},
{
"title": "DDDDDDDDD",
"genres": [
"喜劇", "冒險"。
]
}
],
"Comedy": [
{
"title": "AAAAAAA",
"genres": [
"喜劇".
]
},
{
"標題": "DDDDDDDDD",
"genres": [
"喜劇", "冒險"。
]
}
],
"恐怖": [
{
"title": "EEEEEEEEEEEEEEE",
"genres": [
"Horror".
]
}
]
}
我已經試著復制了答案中的javascript解決方案,在 groupby ngFor angular2,但我被卡住了
。 ItemArray.stream().reduce((identity, accumulator) -> {
accumulator.getGenres().forEach((k) -> {})。
return身份。
});
uj5u.com熱心網友回復:
我認為不使用流會更簡單:
Map<String, List<Item>> itemsByGenre = new HashMap<> ();
for (Item item : items) {
for (String genre : item.genres() ) {
itemsByGenre.computeIfAbsent(genre, g -> new ArrayList<>()).add(item)。
}
這里的關鍵點是,你需要按流派進行爆炸,因為每個專案可以有多個流派。因此,你可以這樣做:
Map<String, List<Item>> itemsByGentre = items.stream()
//make a stream of map entries where the key is the genre, and the value is the item.
.flatMap(i -> i.genres().stream().map(g -> new AbstractMap.SimpleEntry<> (g, i))
.收集()
//現在,按鍵(流派)分組...
收集器.groupingBy(
Map.Entry::getKey,
//并將條目映射到僅有的值(專案),
//和收集專案到一個串列。
Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/322417.html
標籤:
