Apply operations on groupBy result of stream

Viewed 117

I have a List of fruit which contains name and ID

List<Fruit> fruitList = Arrays.asList(new Fruit("apple", 1), new Fruit("orange", 2), new Fruit("orange", 3));

I want to rename the fruit name with name_Id only if duplicate fruit name exists like in case of my list orange will rename to orange_2 and orange_3 but the apple will remain apple.. How can I do it in single stream expression.

The solution that I came up with is

Map<String, List<Fruit>> fruitMap = fruitList.stream().collect(Collectors.groupingBy(Fruit::getName));

        Set<Entry<String, List<Fruit>>> entry = fruitMap.entrySet();

        for (Entry<String, List<Fruit>> en : entry) {
            List<Fruit> fruit = en.getValue();
            if (fruit.size() > 1) {
                fruit.stream().map(d -> {
                    d.setName(d.getName() + "_" + d.getId());
                    return d;
                }).collect(Collectors.toList());
            }
        }    
    }

but this is way more than one stream expression.

3 Answers
Related