Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

java - How to add generic Set to Map (Map<String, Set<String>> map = new TreeMap<>())?

I want to make a phone book with help Map<String, Set<String>> map = new TreeMap<>()

Example:

Anna - 8999
Ira - 8777, 8666
Artur - 5444, 6555

where name is key (String), and the phone number is a Set value, how to specify phone numbers for each name, i.e. each name must have its own Set Numbers

question from:https://stackoverflow.com/questions/65880306/how-to-add-generic-set-to-map-mapstring-setstring-map-new-treemap

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you using Java 8 then try this:

    Map<String, Set<String>> map = new TreeMap<>();
    map.put("Anna", new HashSet(Arrays.asList(8999)));
    map.put("Ira", new HashSet(Arrays.asList(8777, 8666)));
    map.put("Artur",new HashSet(Arrays.asList(5444, 6555)));

If your using Java 9+ then use Set.of. But note this set created using of method is unmodifiable.

Example:

Set.of(8999)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...