0

I have two classes:

public class Cat
{
   public Cat(UUID id, String name)
   {
     this.id = id;
     this.name = name;
   }

   @Getter
   UUID id;

   @Getter
   String name;
}

public class Animal
{
   @Getter
   UUID id;

   @Getter
   String name;
}

And I have two maps:

Map<Cat, Location> map = new HashMap<>();
Map<Animal, Location> map2 = new HashMap<>();

I need to easily convert map2 data into a map. I was able to do it with the following code:

for (Entry<Animal, Location> entry : map2.entrySet())
{
   UUID id = entry.getKey().getId();
   String name = entry.getKey().getName();

   Cat key = new Cat(id, name);
   map.put(key, entry.getValue());
}

return map;

Is there a better way to do this or is the approach I'm taking ok?

Naman
  • 27,789
  • 26
  • 218
  • 353
user6800688
  • 145
  • 3
  • 11
  • 2
    Yes there is. Have you tried reading the javadoc of Stream? Or one of the many tutorials explaining how streams work, and what you can do with them (like map() and collect())? You will learn **a lot** by reading the documentation. – JB Nizet Sep 29 '19 at 18:32
  • 2
    Possible duplicate of [Merge two maps with Java 8](https://stackoverflow.com/questions/40158605/merge-two-maps-with-java-8) – Nicholas K Sep 29 '19 at 18:36
  • Also [related](https://stackoverflow.com/questions/23038673/merging-two-mapstring-integer-with-java-8-stream-api). – Nicholas K Sep 29 '19 at 18:37
  • Consider `map2.forEach((k, v) -> map.put(new Cat(k.getId(), k.getName()), v))`, but also consider dispensing with the maps and adding `location` to `Animal`, since the use of a Map seems to imply that each Animal has one location. – Bohemian Sep 29 '19 at 18:41

2 Answers2

0

You can use Collectors.toMap as :

Map<Cat, Location> map = map2.entrySet().stream()
        .collect(Collectors.toMap(
                entry -> new Cat(entry.getKey().getId(), entry.getKey().getName()),
                Map.Entry::getValue,
                (a, b) -> b));
Naman
  • 27,789
  • 26
  • 218
  • 353
0

You could use the toMap() collector with the merge overload :

Map<Cat, Location> map =
map2.entrySet()
    .stream()
    .collect(toMap(e-> new Cat(e.getKey().getId()), entry.getKey().getName(), 
                   Entry::getValue, (a,b)->b ));

Or maybe simpler without stream :

Map<Cat, Location> map = new HashMap<>();
map2.forEach( (k,v) -> map.put(new Cat(k.getId(), k.getName()), v) );
davidxxx
  • 125,838
  • 23
  • 214
  • 215