Generate a unique collection of values from a collection that contains duplicate values

Overview

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.

Sample code

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() + "]");
        });
    }
}

Execute

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

Generate a unique collection of values from a collection that contains duplicate values
A collection of RSpecs that I used frequently
A collection of commands that were frequently used on heroku
A collection of Eclipse shortcuts that new graduates find useful
A collection of phrases that impresses the "different feeling" of Java and JavaScript
[Rails] A collection of tips that are immediately useful for improving performance
Significance of interface learned from Java Collection
A program that calculates factorials from 2 to 100
Find the difference from a multiple of 10
It's just now, but a collection of commands that frequently appear in Rails