我目前正在制作這段代碼,它假設輸出一個人的名字,但名單上沒有寫他/她的名字。我只是想問一下如何使用 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;
}
}
uj5u.com熱心網友回復:
只需在回傳您的 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);
}
}
我只是檢查應該存在的集合中缺少哪個值。
uj5u.com熱心網友回復:
另一種使用集合功能的方法是在回傳之前添加以下內容:
//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-
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/408244.html
標籤:
