You say you want to sort by value, but you don't have that in your code. Pass a lambda (or method reference) to sorted to tell it how you want to sort.
And you want to get the keys; use map to transform entries to keys.
List<Type> types = countByType.entrySet().stream()
.sorted(Comparator.comparing(Map.Entry::getValue))
.map(Map.Entry::getKey)
.collect(Collectors.toList());
Answer from Jesper on Stack OverflowYou say you want to sort by value, but you don't have that in your code. Pass a lambda (or method reference) to sorted to tell it how you want to sort.
And you want to get the keys; use map to transform entries to keys.
List<Type> types = countByType.entrySet().stream()
.sorted(Comparator.comparing(Map.Entry::getValue))
.map(Map.Entry::getKey)
.collect(Collectors.toList());
You have to sort with a custom comparator based on the value of the entry. Then select all the keys before collecting
countByType.entrySet()
.stream()
.sorted((e1, e2) -> e1.getValue().compareTo(e2.getValue())) // custom Comparator
.map(e -> e.getKey())
.collect(Collectors.toList());
Based on Collectors documentation it's as simple as:
Map<String, Choice> result =
choices.stream().collect(Collectors.toMap(Choice::getName,
Function.identity()));
If your key is NOT guaranteed to be unique for all elements in the list, you should convert it to a Map<String, List<Choice>> instead of a Map<String, Choice>
Map<String, List<Choice>> result =
choices.stream().collect(Collectors.groupingBy(Choice::getName));
It looks like all you need is flatMap the values of the original Map and then continue processing as you currently do:
Collection< PublicationSession > wantedPublications =
effectiveDatePublicationMap.values() // Collection<List<PublicationSession>>
.stream() // Stream<List<PublicationSession>>
.flatMap(list->list.stream()) // Stream<PublicationSession>
.filter(pub -> PublicationStatus.valueOf(pub.getPublishStatus()) == PublicationStatus.COMPLETE)
.sorted(Comparator.comparing(PublicationSession::getCreateTime))
.collect(toMap(p -> p.getPublicationSession().getEffDateTime(), UnaryOperator.identity(), PICK_LATEST))
.values();
To obtain the same result of your iterative code
List< PublicationSession> publicationsToFilter = new ArrayList<>();
for (List< PublicationSession> sessions : effectiveDatePublicationMap.values()) {
publicationsToFilter.addAll(sessions);
}
with streams you first have to use flatMap to transoform your stream of List<PublicationSession> in a stream of PublicationSession, and then collect all of them in a list with collect(Collectors.toList())
List<PublicationSession> publicationsToFilter = effectiveDatePublicationMap.values()
.flatMap(Collection::stream)
.collect(Collectors.toList());
Before collecting the result, you can filter or sort as you wish.