在 HashMap 中打印唯一字符串
Printing unique strings in HashMap
我目前正在编写这段代码,它假设输出某个人的名字,而列表中没有写 his/her 名字。
我只想问一下如何使用 Map
制作这样的输出
输出:
{安德鲁}
解释:Jay 写了 Susan,Susan 写了 Jay,Andrew 写了 Anna,Anna 写了 Jay,但没有人写 Andrew。
谢谢!
public class Main {
public static void main(String[] args) {
Main func = new Main();
System.out.println(func.test("Jay:Susan,Susan:Jay,Andrew:Anna,Anna:Jay"));
}
public PriorityQueue test(String c) {
Map < String, String > hmap = new HashMap < > ();
PriorityQueue a = new PriorityQueue();
String b = c.replaceAll("[,]", "-");
System.out.println(b);
String[] d = b.split("-");
for (int i = 0; i < d.length; i++) {
String names = d[i];
String[] temp;
String splitter = ":";
temp = names.split(splitter);
String aName = temp[0];
String cName = temp[1];
hmap.put(aName, cName);
}
System.out.println(hmap);
return a;
}
}
只需在返回 priorityQueue 之前添加此代码段:
Set<String> keys= new HashSet<>( hmap.values());
for(Map.Entry<String, String> map: hmap.entrySet())
{
String key=map.getKey();
if(!keys.contains(key))
{
System.out.println(key);
a.add(key);
}
}
我只是在检查本应存在的集合中缺少哪个值。
另一种使用集合功能的方法是在返回之前添加以下内容:
//Extract all the voters into a new hashset, this will be modified
Set<String> missing = new HashSet<>( hmap.keySet());
//Use Collections.removeAll() to remove all the values from the keyset
missing.removeAll(hmap.values());
//Add the results to your queue
a.addAll(missing);
看看:
https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#removeAll-java.util.Collection-
我目前正在编写这段代码,它假设输出某个人的名字,而列表中没有写 his/her 名字。 我只想问一下如何使用 Map
制作这样的输出输出: {安德鲁}
解释:Jay 写了 Susan,Susan 写了 Jay,Andrew 写了 Anna,Anna 写了 Jay,但没有人写 Andrew。
谢谢!
public class Main {
public static void main(String[] args) {
Main func = new Main();
System.out.println(func.test("Jay:Susan,Susan:Jay,Andrew:Anna,Anna:Jay"));
}
public PriorityQueue test(String c) {
Map < String, String > hmap = new HashMap < > ();
PriorityQueue a = new PriorityQueue();
String b = c.replaceAll("[,]", "-");
System.out.println(b);
String[] d = b.split("-");
for (int i = 0; i < d.length; i++) {
String names = d[i];
String[] temp;
String splitter = ":";
temp = names.split(splitter);
String aName = temp[0];
String cName = temp[1];
hmap.put(aName, cName);
}
System.out.println(hmap);
return a;
}
}
只需在返回 priorityQueue 之前添加此代码段:
Set<String> keys= new HashSet<>( hmap.values());
for(Map.Entry<String, String> map: hmap.entrySet())
{
String key=map.getKey();
if(!keys.contains(key))
{
System.out.println(key);
a.add(key);
}
}
我只是在检查本应存在的集合中缺少哪个值。
另一种使用集合功能的方法是在返回之前添加以下内容:
//Extract all the voters into a new hashset, this will be modified
Set<String> missing = new HashSet<>( hmap.keySet());
//Use Collections.removeAll() to remove all the values from the keyset
missing.removeAll(hmap.values());
//Add the results to your queue
a.addAll(missing);
看看: https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#removeAll-java.util.Collection-