/**
* 获取列表数据中的唯一名称
*
* @param nameArr 要列表数据匹配的名称数组
* @param indexArr 要插入副本标识的nameArr中的下标
* @param prefix 替换名称的前缀
* @param suffix 替换名称的后缀
* @param dataList 列表数据
* @return 唯一名称
*/
public static String getUniqueName(String[] nameArr, Integer[] indexArr, String prefix, String suffix, List<NameData> dataList) {
String name = String.join("", nameArr);
boolean match = dataList.stream().anyMatch(item -> item.getName().equals(name));
if (!match) {
return name;
}
prefix = prefix == null ? "" : prefix;
suffix = suffix == null ? "" : suffix;
int num = 1;
while (true) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < nameArr.length; ++i) {
for (Integer index : indexArr) {
if (i == index) {
sb.append(String.format("%s%d%s", prefix, num, suffix));
}
}
sb.append(nameArr[i]);
}
String rName = sb.toString();
match = dataList.stream().anyMatch(item -> item.getName().equals(rName));
if (!match) {
return rName;
}
++num;
}
}
public static void main(String[] args) {
List<NameData> nameData = new ArrayList<>();
NameData nameData1 = new NameData();
nameData1.setName("张三");
nameData.add(nameData1);
NameData nameData2 = new NameData();
nameData2.setName("李四");
nameData.add(nameData2);
NameData nameData3 = new NameData();
nameData3.setName("李四(1)");
nameData.add(nameData3);
NameData nameData4 = new NameData();
nameData4.setName("李四(1).txt");
nameData.add(nameData4);
NameData nameData5 = new NameData();
nameData5.setName("李四.txt");
nameData.add(nameData5);
String uniqueName = getUniqueName(new String[]{"李四", ".txt"}, new Integer[]{1}, "-副本(", ")", nameData);
System.out.println(uniqueName);
}