使用两个字符串生成唯一标识符

我想知道如何使用两个字符串生成唯一标识符。 我的要求是为特定文档生成唯一标识符。 对于id生成,必须使用文档’name’和’version’。 应该有办法从特定文档的唯一标识符中取回“名称”和“版本”。 有没有办法在java中使用UUID? 或者这样做的最佳方式是什么。 我们可以为此目的使用散列或编码吗?如果是这样,怎么办?

我不知道你为什么要使用2个字符串来生成唯一ID,在某些情况下可能无法保留唯一性。 java.util.UUID为您的案例提供了有用的方法。 看看这个用法:

 import java.util.UUID; ... UUID idOne = UUID.randomUUID(); UUID idTwo = UUID.randomUUID(); 

如果您对使用这种方式生成的ID不满意,可以附加参数(如名称和版本) 附加/前置到生成的ID中。

执行此操作的最佳方法是使用分隔符连接字符串,这些分隔符通常不会出现在这些字符串中

例如

 String name = .... String version = ..... String key = name + "/" + version; 

您可以使用split("/")获取原始名称和版本

您可以使用静态工厂方法randomUUID()来获取UUID对象:

 UUID id = UUID.randomUUID(); 

要将id与版本组合在一起,请提出一个您知道不会在任何字符串中的分隔符,例如/_ 。 然后你可以split该分隔符或使用正则表达式来提取你想要的东西:

 String entry = id + "_" + version; String[] divided = entry.split(delimiter); //or using regex String entry= "idName_version"; //delimiter is "_" String pattern = "(.*)_(.*)"; Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(example); if (m.find()) { System.out.println(m.group(1)); //prints idName System.out.println(m.group(2)); //prints version } 

如果您不想创建UUID,请保持纯字符串

 String.format("%s_%s_%s_%s", str1.length(), str2.length(), str1, str2); 

用以下测试

 Pair.of("a", ""), // 'a' and '' into '1_0_a_' Pair.of("", "a"), // '' and 'a' into '0_1__a' Pair.of("a", "a"), // 'a' and 'a' into '1_1_a_a' Pair.of("aa", "a"), // 'aa' and 'a' into '2_1_aa_a' Pair.of("a", "aa"), // 'a' and 'aa' into '1_2_a_aa' Pair.of("_", ""), // '_' and '' into '1_0___' Pair.of("", "_"), // '' and '_' into '0_1___' Pair.of("__", "_"), // '__' and '_' into '2_1_____' Pair.of("_", "__"), // '_' and '__' into '1_2_____' Pair.of("__", "__"), // '__' and '__' into '2_2______' Pair.of("/t/", "/t/"), // '/t/' and '/t/' into '3_3_/t/_/t/' Pair.of("", "") // '' and '' into '0_0__' 

这是有效的,因为开头创建了一种使用数字不能存在的分隔符来解析以下内容的方法,如果使用了像’0’这样的分隔符,则会失败

其他示例依赖于任一字符串中不存在的分隔符

 str1+"."+str2 // both "..","." and ".",".." result in "...." 

编辑

支持组合’n’字符串

 private static String getUniqueString(String...srcs) { StringBuilder uniqueCombo = new StringBuilder(); for (String src : srcs) { uniqueCombo.append(src.length()); uniqueCombo.append('_'); } // adding this second _ between numbers and strings allows unique strings across sizes uniqueCombo.append('_'); for (String src : srcs) { uniqueCombo.append(src); uniqueCombo.append('_'); } return uniqueCombo.toString(); }