如何重命名ArrayList中的重复元素

I have an Arraylist of names and some of these names repeat in this whole list, and i would like to change duplicates into incremented names: e.g. hlist= 'Max','Rose', 'Monica', 'Rose', 'Alex', 'Alex', 'Alex' and i need to receive: updated_hlist = 'Max','Rose', 'Monica', 'Rose_1', 'Alex', 'Alex_1', 'Alex_2'

我的代码:

List<OutputField> hList;
hList = hBlock.getOutputField();
List<OutputField> duplicatedList = new ArrayList<OutputField>();
            Set<OutputField> mySet = new LinkedHashSet<OutputField>();
            for (OutputField thisField : hBlock.getOutputField()) {
                if (mySet.contains(thisField.getName())) {
                    int i = 1;
                    while (mySet.contains(thisField.getName() + i)) {
                        i++;
                    }
                    thisField = (thisField.getName()) + i; // here sth wrong
                }
                mySet.add(thisField.getName()); // here sth wrong
            }

评论
emagni
emagni

如果要使用流,则可以解决以下问题:

List<String> result = list.stream()
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
        .entrySet().stream()
        .flatMap(entry ->
                IntStream.range(0, entry.getValue().intValue())
                        .mapToObj(s -> s == 0 ? entry.getKey() : String.format("%s_%d", entry.getKey(), s)))
        .collect(Collectors.toList());

产出

[Alex, Alex_1, Alex_2, Max, Rose, Rose_1, Monica]
点赞
评论