简体   繁体   中英

HashSet of Strings and retrieval of only the first word of each element

如果我有一个HashSet<String> ,我如何只检索 Set 的每个元素的第一个单词?

To retrieve the first word of each String in your set, try this:

Collection<String> firstWords = set.stream()
    .map(s -> s.split(" ")[0]) // split on spaces, take first element of the split
    .collect(Collectors.toSet());

If you want to retain duplicates, change Collectors.toSet() to Collectors.toList()

You can get the first element of a set like this:

if (! set.isEmpty()) {
    first = set.iterator().next();
}

However, the "first" element is an arbitrary thing for a HashSet , since they are unordered, or as the javadoc says it:

It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time.

Instead of HashSet , you could use a LinkedHashSet , which keeps insertion order , or a TreeSet , with is sorted , so in both cases "first" is well-defined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM