gurehbgui
gurehbgui

Reputation: 14674

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?

E.g. 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.

Upvotes: 0

Views: 1806

Answers (4)

Mena
Mena

Reputation: 48404

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}

Upvotes: 4

DwB
DwB

Reputation: 38290

  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.

Upvotes: 1

Uncle Iroh
Uncle Iroh

Reputation: 6045

private enum Animals {
   Cat,
   Dog,
   Cow,
   Sheep,
   Horse 
}

Animals.Cat.ordinal() -- gives you the number. Animals.valueOf("Cat"); -- match strings with.

Upvotes: 1

Jayram
Jayram

Reputation: 19578

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.

Upvotes: 1

Related Questions