我是Java新手8 lambda表達式。如何檢索根據標記爲「否」的標籤排序的收藏標籤列表?
我有一個List<Post>
其中每個Post
可以屬於多個帖子。
class Post{
String name;
List<String> tags;
....
}
我希望檢索基於無後通過其標籤排序最喜歡的標籤列表。如何使用lambda表達式來實現它?以JSON形式存儲在MongoDB中
樣品輸入:
[
{
"name": "java with spring",
"tags": [
"java",
"spring"
]
},
{
"name": "spring with mongodb",
"tags": [
"java",
"spring",
"mongodb"
]
},
{
"name": "spring with hibernate",
"tags": [
"java",
"spring",
"hibernate"
]
}
]
預期輸出:
java,spring,mongodb,hibernate
以下是我在下面的答案後試圖:;
List<Post> posts = ...
List<String> tags = new ArrayList<>();
Map<String, Integer> map = new TreeMap<String, Integer>();
// get list of all tags
posts.stream().forEach(post -> tags.addAll(post.getTags()));
// populate map with tag and its count (frequency)
tags.stream().forEach(tag -> map.put(tag, map.get(tag) == null ? 1 : map.get(tag) + 1));
Comparator<Entry<String, Integer>> byValue = (entry1, entry2) -> entry1.getValue().compareTo(entry2.getValue());
// sort the map by value and return the sorted keys as favorite tags
List<String> favoriteTags = map.entrySet().stream().sorted(byValue.reversed()).map(e -> e.getKey()).collect(Collectors.toList())
是的,它是我上次編輯的簡化版本。謝謝 – Braj 2015-04-04 19:19:32
沒問題,但我對Java 8 lambda表達式也很陌生,我想知道是否有辦法在單個表達式中實現這一點。我很確定有一種方法... – Neumann 2015-04-04 19:20:29