我是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)有多少个不同的节点连接到每个节点
我正在努力决定是否真的需要编写自己的课程,还是有更简单的方法?
答案 0 :(得分:9)
您可以创建自定义类来存储字符串对,然后使用HashMap
来跟踪计数
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);
}
答案 1 :(得分:1)
Hashtable(数据结构)应该适合您的要求。在java中,您可以考虑键入HashMap<String,Integer>
key是字符串对,Integer是count:
类似的东西:
{
"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编写的,因此可能会有拼写错误。
答案 2 :(得分: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
并制作Pair
implement
Comparable
,则会有一个已排序的对话列表
Set<Pair> pairs = new TreeSet<Pair>();
..
System.out.println(pairs);
此外,您可以结合使用List
和Set
并应用一些逻辑来确定重复的确切数量等,还可以浏览removeAll
和retainAll
实施逻辑。
此外,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;