D
D
devpy142021-01-11 21:12:28
Java
devpy14, 2021-01-11 21:12:28

How to convert Collection(map.values()) to normal Set?

There is a Map:
{English=[Antony], Chemistry=[John], Music=[Antony]}
When using map.values() returns , you need to translate this whole thing into Set, getting rid of duplicates. I only came to the trail. option:

Set<String> uniqueStudents = new HashSet<>();
        for (List<String> listName: map.values()) {
            uniqueStudents.add(listName.get(0));
        }
        System.out.println(uniqueStudents); // [John, Antony]


Maybe someone knows a better solution?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BorLaze, 2021-01-11
@devpy14

Or the question is strange, or one of the two ... what does not suit the simplest solution?

Set<String> uniqueStudents = new HashSet<>(map.values());

PS: didn't notice that map values ​​are arrays of strings, not strings. Then you really need to:
Set<String> set = map.values().stream()
                               .map(a -> a[0])
                               .collect(Collectors.toSet());

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question