This is a sample code that returns a unique collection of values by serially numbering the duplicated values from a collection with duplicate values as shown below.
List<String> list = Arrays.asList("a", "b", "c", "a", "b", "b", "d", "a", "b");
Note that non-overlapping values (or the first value) are not given a serial number, and when they are duplicated, a serial number after 2 is added. For example
a, a, b, c, c, c
Is
a, a_2, b, c, c_2, c_3
To do.
public static class UniqueValue {
private Map<String, Integer> cache = new HashMap<>();
String get(String name, Integer idx) {
String tmp;
if (idx > 1) {
tmp = name + "_" + idx.toString();
} else {
tmp = name;
}
if (!cache.containsKey(tmp)) {
cache.put(tmp, idx);
return tmp;
}
//If there are duplicates, add serial numbers and recurse
return get(name, idx + 1);
}
void dump() {
cache.entrySet().forEach(e -> {
System.out.println("dump: key=[" + e.getKey() + "] i=[" + e.getValue() + "]");
});
}
}
List<String> list = Arrays.asList("a", "b", "c", "a", "b", "b", "d", "a", "b");
UniqueValue un = new UniqueValue();
Set<String> unique = list.stream()
.sorted()
.map(name -> un.get(name, 1))
.collect(Collectors.toSet());
unique.forEach(System.out::println);
// → a
// → b
// → c
// → a_3
// → b_2
// → d
// → a_2
// → b_4
// → b_3
un.dump();
// → dump: key=[a] i=[1]
// → dump: key=[b] i=[1]
// → dump: key=[c] i=[1]
// → dump: key=[a_3] i=[3]
// → dump: key=[b_2] i=[2]
// → dump: key=[d] i=[1]
// → dump: key=[a_2] i=[2]
// → dump: key=[b_4] i=[4]
// → dump: key=[b_3] i=[3]
Recommended Posts