简体   繁体   English

如何获取字符串列表的唯一ID?

[英]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. -匹配字符串。

  1. build a set containing the values. 建立一个包含值的集合。
  2. build an array containing the set values (see Set.toArray()). 构建一个包含设置值的数组(请参见Set.toArray())。
  3. The index of the item in array is the integer identifier for the item. 数组中该项目的索引是该项目的整数标识符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM