1

I am trying to create a unique list. I can not use a "Set" because I need to assign some of the values as I iterate though it.

Right now I doing this to create a unique list. Does anyone know a better way?

List<Thing> things = previousThings.stream()
                       .collect(Collectors.toSet()).stream()
                       .collect(Collectors.toList());

I was thinking that if I convert it to a set and the back to a list it would eliminate any duplicate entries. I think it needs to be a list so that I can use "List.set(..)" to update according to what might already be in my repository.

for(int i = 0; i < things.size(); i++) {
  if(things.get(i).id == null) {
    existingThing = thingRepository.getByName(things.get(i).getName());
    if(existingThing != null) {
      things.set(i, existingThing);
    } else {
      things.set(i, thingRepository.save(things.get(i));
    }
  }
}
Alexis C.
  • 91,686
  • 21
  • 171
  • 177
B Roy Dawson
  • 611
  • 1
  • 6
  • 18
  • 3
    Replace `.collect(Collectors.toSet()).stream()` with `.distinct()` – Louis Wasserman Aug 03 '16 at 00:08
  • That would normally work, but I should have mentioned that I need to use a different method than the .equals() for the comparison because it uses id and I am looking for unique names. Is there a similar method that will allow you to provide a lambda for comparison? @LouisWasserman – B Roy Dawson Aug 03 '16 at 16:29
  • What do you call "unique" ? Based on the objects `equals()` method ? Are they Immutable ? – lvr123 Aug 04 '16 at 12:13
  • I wanted them unique based off thing.name @Ivr123 – B Roy Dawson Aug 04 '16 at 16:37

1 Answers1

0

I thought before that I wouldn't be able to use the .distinct() because it uses .equals() which is based off of 'Thing.id' and some of the 'Things' don't have an 'id' yet. Then I realized that by the end of the forLoop everything is assigned an id by the repository.

List<Thing> things = previousThings;
for(int i = 0; i < things.size(); i++) {
  if(things.get(i).id == null) {
    existingThing = thingRepository.getByName(things.get(i).getName());
    if(existingThing != null) {
      things.set(i, existingThing);
    } else {
      things.set(i, thingRepository.save(things.get(i));
    }
  }
}
List<Thing> distinctThings = things.stream().distinct().collect(Collectors.toList);
B Roy Dawson
  • 611
  • 1
  • 6
  • 18