Reputation: 14674
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
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
Reputation: 38290
Upvotes: 1
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
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