8

我是Java的初学者。我有一些节点的样本数据:

A -> B

B -> F

C -> R

A -> B

B -> C

R -> C

我已经取出了 2 个列表:[A,B,C,A,B,R] 和 [B,F,R,B,C,C]

但是,我应该如何存储对 [AB, BF, CR, AB, BC, RC] 以便我可以找到唯一的对?唯一的意思是 AB 不等于 BA 。

1)所以基本上我想识别独特的对。

2)我还想计算每个唯一对出现的次数。

编辑:

3)我也有兴趣找出每个节点连接到多少个不同的节点。

4)每个节点有多少个不同的节点连接

我正在努力决定是否真的需要编写自己的课程或者是否有更简单的方法?

4

3 回答 3

10

您可以创建一个自定义类来存储字符串对,然后使用 aHashMap来跟踪计数

public class StringPair {
   String leftString;
   String rightString;

   //NOTE: override hashcode and equals methods
}

然后您可以HashMap用于跟踪计数:

Map<StringPair, Integer> pairCountMap = new HashMap<StringPair, Integer>();

if(pairCountMap.containsKey(aPairObject)) {
   pairCountMap.put(aPairObject, pairCountMap.get(aPairObject)+1);
} else {
   pairCountMap.put(aPairObject, 0);
}
于 2013-05-17T20:58:09.007 回答
2

哈希表(数据结构)应该可以满足您的要求。在java中,你可以考虑类型HashMap<String,Integer>

key 是字符串对,Integer 是计数:

就像是:

{
"AB":2,
"CR":1,
"BF":1,
...

}

找到唯一对的复杂性是O(n)

编辑

似乎将代码放在这里有助于解释解决方案:

Map<String, Integer> map = new HashMap<String,Integer>();

//you have two lists with those strings, called list1 and list2.
// list1<String> and list2<String> have same size

String key = null;
for(int i=0;i<list1.size();i++){
    key = list1.get(i) + list2.get(i);
    if(map.containsKey(key))
        map.get(key)++;
    else
        map.put(key,1);
}

//now the map has been filled, you can go through the map, 
//and check the value, if value == 1, then the key is unique.
//for those value >1, you know, which string pair is not unique, 
// and how many times it shows.

代码不是用IDE编写的,所以可能有错别字。

于 2013-05-17T21:02:51.340 回答
1

您需要一个类来指定对:

public class Pair{
 String prv;
 String next;
 //override hashcode and equals
}

如果您使用Set并填写所有对,您最终将拥有唯一的对:

Set<Pair> pairs = new HashSet<Pair>();
..
pairs.add(new Pair(prv, next));
int uniquePairs = pairs.size();

如果你使用TreeSet和 make Pair implement Comparable,你将有一个排序的对列表

Set<Pair> pairs = new TreeSet<Pair>();
..
System.out.println(pairs);

此外,您可以结合使用ListSet应用一些逻辑来计算重复的确切数量等,也可以探索removeAllretainAll实现逻辑。

此外,Map似乎不适合您的用例,因为类可以包装所需的映射,并且列表或集合将有助于在多对上应用所需的逻辑。

要获得原始对总数的计数:

Set<Pair> pairs = new HashSet<Pair>();
int count =0;
while(..) { //iterating over list of pairs
    pairs.add(new Pair(prv, next));
    count ++;
   }
int uniquePairs = pairs.size();
int totalPairs = count;
于 2013-05-17T21:14:15.467 回答