简体   繁体   中英

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?

Eg the list looks like ["Cat","Dog","Cow","Cat","Rat"] the result should be:

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.

You could use a HashMap<Integer, String> . The key would be the index in your current List , while the value would be the actual 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.

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.valueOf("Cat"); -- match strings with.

  1. build a set containing the values.
  2. build an array containing the set values (see Set.toArray()).
  3. The index of the item in array is the integer identifier for the item.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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