[英]If I have two keys with equal value, how do I return a Set<String> kinda (value + " - " + key ", " + key)?
This code works only when I have a pair like name(value) + number(key), but I'm stuck with situation like - name + number, number.此代码仅在我有一对名称(值)+数字(键)时才有效,但我遇到了诸如-名称+数字,数字之类的情况。 It returns name + number1, name + number2
它返回名称+编号1,名称+编号2
public Set<String> getAllContacts() {
TreeSet<String> contacts = new TreeSet<>();
if (phoneBook.isEmpty()) {
return new TreeSet<>();
} else {
for (Map.Entry<String, String> entry : phoneBook.entrySet()) {
contacts.add(entry.getValue() + " - " + entry.getKey());
}
}
return contacts;
}
Basically you want to invert key
and value
of your phoneBook
map.基本上你想反转你的电话簿
phoneBook
的key
和value
。 Since one name
can have multiple number
s according to your example the output structure should be Map<String, List<String>>
.由于根据您的示例,一个
name
可以有多个number
,因此 output 结构应该是Map<String, List<String>>
。 With this name oriented phone book you can easily create your contact collection.使用这个以姓名为导向的电话簿,您可以轻松地创建您的联系人集合。 Eg
例如
Map<String, List<String>> phoneBookByName = new HashMap<>();
phoneBook.forEach((k, v) -> {
List<String> numbers = phoneBookByName.computeIfAbsent(k, s -> new ArrayList<>());
numbers.add(v);
});
TreeSet<String> contacts = new TreeSet<>();
phoneBookByName.forEach((k, v) -> contacts.add(k + " - " + String.join(", ", v)));
return contacts;
or using streams或使用流
Map<String, List<String>> phoneBookByName = phoneBook.entrySet().stream()
.collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList())));
return phoneBookByName.entrySet().stream()
.map(entry -> entry.getKey() + " - " + String.join(", ", entry.getValue()))
.collect(Collectors.toCollection(TreeSet::new));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.