1

I want to reverse the values in the Set<String>

So, I am creating a Set<String> of keys from some HashMap And printing out the values i.e. keys.

Set<String> movies =  movieList.keySet();
for(String movie : movies) {
    output += movie + "\n";
}

I need to reverse the values of the Set<String> from last value to first values Is this possible?  

1
  • 9
    Elements in a Set are not ordered... a LinkedHashSet on the other hand... Commented Apr 22, 2018 at 6:36

5 Answers 5

1

If you want the keys of the Map to be ordered, you must use a different Map implementation, since the keys of a HashMap are not ordered.

You can use a TreeMap. You can pass to its constructor a Comparator that would determine the ordering of the keys. That would determine the order of the keys in the Set returned by keySet().

For example, if you want your movies to be sorted according to reversed lexicographical order:

Map<String,Movie> moviesByName = new TreeMap<>((s1,s2)->s2.compareTo (s1));

or, as lexicore suggested:

Map<String,Movie> moviesByName = new TreeMap<>(Comparator.<String>naturalOrder().reversed());
Sign up to request clarification or add additional context in comments.

7 Comments

Is it possible to get an example for clarity please?
2 questions. String and Movie are the key/value of the hashmap here? And can you elaborate what (s1,s2)->s2.compareTo (s1) means ?
@Shaz 1. yes 2. that's a lambda expression (available since Java 8). It's a shorter way to implement the Comparator<String> interface.
Did you try reading the JavaDoc of java.util.Map? And are you familiar with Java 8 streams and lambda functions?
@Eran FTFY: Map<String,String> moviesByName = new TreeMap<>(Comparator.<String>naturalOrder().reversed());. Not sure why type inference didn't work.
|
1

If you are using Java8 you can try:

List<String> sorted = movieList.keySet().stream()
                .sorted(Collections.reverseOrder())
                .collect(Collectors.toList());

Or even better if you want only the output String:

String output = movieList.keySet().stream()
                .sorted(Collections.reverseOrder())
                .collect(Collectors.joining("\n"));

But if the intent is to just reverse the map.keySet as Andreas suggested ... then

ArrayList<String> list = new ArrayList<>(movieList.keySet());
Collections.reverse(list);
//list is now in reverse order of the keySet

2 Comments

That would sort the values in reverse of the keys natural order, not in reverse of the order in the keySet.
Although you are right, but The question in its original context is ambiguous, because the Set from a Map already doesn't have any guarantee that you know the order in which it was populated, so the Set here is not a pure Set with intention of preserving order, also there is a side question between the lines of getting a concatenated result in String. otherwise only a reverse loop could've solved the problem.
1

JEP 431: Sequenced Collections (release 9/19/23) in Java 21 has a reversed() method to SortedSet. This reversed view of the SortedSet can iterate in descending order.

SortedSet<String> movies =  movieList.keySet();
for(String movie : movies.reversed()) {
    output += movie + "\n";
}

That being said you may want to use a StringBuilder() for your output variable.

Comments

0

A key quality of a Set is that it not sorted. So you need to use another data structure to achieve this goal. The simplest solution may be a List, but then you loose the quality of a Set to not contain entires that are equal (entry.equals(otherentry) == true)

If you want to retrieve entries in the order of filling (or reverse) and still want to retain the Set quality, you may use a LinkedHashSet

The solution of Eran is also possible, but there you need to create a comparator that results in the order of addition to the TreeMap.

Comments

0
After getting values stored in a Set, Add all values of Set into a List then apply reverse function of list. Below is an example

import java.util.*;
class Test
{
public static void main(String args[])
{
Set h=new LinkedHashSet();
List h2 = new LinkedList();
h.add("Lovely");
h.add("Professional");
h.add("University");
h2.addAll(h);   
System.out.println(h);
Collections.reverse(h2);
System.out.println(h2);
}
}   

1 Comment

If you had formatted code to be readable, I might have up-voted it. But then again, an ArrayList created straight from h would be better. Besides the question is not about an ordered LinkedHashSet, but an unordered keySet from a HashMap .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.