[英]How to get a Unique ID for a list of strings?
How can I get a Unique ID (as a integer) for a List of Strings? 如何获得字符串列表的唯一ID(作为整数)?
Eg the list looks like ["Cat","Dog","Cow","Cat","Rat"]
the result should be: 例如,列表看起来像
["Cat","Dog","Cow","Cat","Rat"]
,结果应为:
1 -> Cat
2 -> Dog
3 -> Cow
4 -> Rat
I need to save this and new structure. 我需要保存此结构和新结构。
EDIT: Its important, that Cat
is only one time in the new structure. 编辑:重要的是,
Cat
在新结构中只有一次。
You could use a HashMap<Integer, String>
. 您可以使用
HashMap<Integer, String>
。 The key would be the index in your current List
, while the value would be the actual String
. 键将是当前
List
的索引,而值将是实际的String
。
Example: 例:
List<String> myList = new ArrayList<String>();
// no identical Strings here
Set<String> mySet = new LinkedHashSet<String>();
myList.add("Cat"); // index 0
myList.add("Dog"); // index 1
myList.add("Cow"); // etc
myList.add("Cat");
myList.add("Rat");
mySet.add("Cat"); // index 0
mySet.add("Dog"); // index 1
mySet.add("Cow"); // etc
mySet.add("Cat"); // index 0 - already there
mySet.add("Rat");
Map<Integer, String> myMap = new HashMap<Integer, String>();
for (int i = 0; i < myList.size(); i++) {
myMap.put(i, myList.get(i));
}
System.out.println(myMap);
Map<Integer, String> myOtherMap = new HashMap<Integer, String>();
int i = 0;
for (String animal: mySet) {
myOtherMap.put(i++, animal);
}
System.out.println(myOtherMap);
Output: 输出:
{0=Cat, 1=Dog, 2=Cow, 3=Cat, 4=Rat}
{0=Cat, 1=Dog, 2=Cow, 3=Rat}
If it's only unique within a process, then you can use an AtomicInteger
and call incrementAndGet()
each time you need a new value. 如果它仅在流程中唯一,则可以在每次需要新值时使用
AtomicInteger
并调用AtomicInteger
incrementAndGet()
。
Else you can try this 否则你可以试试这个
int uniqueId = 0;
int getUniqueId()
{
return uniqueId++;
}
Add synchronized if you want it to be thread safe. 如果希望线程安全,请添加同步。
private enum Animals {
Cat,
Dog,
Cow,
Sheep,
Horse
}
Animals.Cat.ordinal()
-- gives you the number. Animals.Cat.ordinal()
-给您数字。 Animals.valueOf("Cat");
-- match strings with. -匹配字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.