1

I am a very new to mapstruct. I am trying to convert List to Map, I've searched a lot online, I've got some solutions like its not yet implemented in mapstruct seems. I will be glad if someone could able to provide some alternative solution. All I am looking to convert mapping as below:

@Mapping
Map<String, Object> toMap(List<MyObj>)

@Mapping
    List<MyObj> toList(Map<String, Object>)

where MyObj as below:

class MyObj {
  String key; //map key
  String value; //map value
  String field1;
}

In above, only use key and value fields from MyObj class. I've found one solution but below is converting some object to MAP, but using Jackson below:

@Mapper
public interface ModelMapper {

  ObjectMapper OBJECT_MAPPER = new ObjectMapper();

  default HashMap<String, Object> toMap(Object filter) {
    TypeFactory typeFactory = OBJECT_MAPPER.getTypeFactory();
    return OBJECT_MAPPER.convertValue(filter, typeFactory.constructMapType(Map.class, String.class, Object.class));
  }
}

is there anyway now to implement using mapstruct?

john
  • 925
  • 1
  • 12
  • 20
  • Not aware of mapstruct, but with java stream api also you can change data structure easily. https://stackoverflow.com/questions/20363719/java-8-listv-into-mapk-v – www.hybriscx.com Nov 08 '19 at 05:53
  • Actually I need solution using mapstruct only! – john Nov 08 '19 at 06:09
  • i found this with a quick searc https://github.com/mapstruct/mapstruct/issues/850 seems like you need to create toMap function in Component instead of mapper. – www.hybriscx.com Nov 08 '19 at 06:12

1 Answers1

4

Map struct doesn't have implicit conversion for your desired List to Map. You can have a custom mapping method as follows:

@Mapper
public interface FooMapper {


    default Map<String, Foo> convertFooListToMap(List<Foo> foos) {
      // custom logic using streams or however you like.
    }
}

Other options include custom mapper implementations that you write and refer with something like @Mapper(uses=CustomMapper.class)

Karthik R
  • 5,523
  • 2
  • 18
  • 30
  • 1
    Or alternatively, just add the above to the mapper you are writing. The idea is that MapStruct takes away the bulk of mapping, but there will always be some stuff remaining requiring handwritten code. MapStruct recognises the method (looking for one that can convert `List` to `Map – Sjaak Nov 10 '19 at 10:29
  • @Sjaak can you help me on this: https://stackoverflow.com/questions/58842694/mapstruct-collectionmappingstrategy-issues-unable-to-do-update-operations – john Nov 13 '19 at 20:15
  • @karthik : can you help me on this: https://stackoverflow.com/questions/58842694/mapstruct-collectionmappingstrategy-issues-unable-to-do-update-operations – john Nov 13 '19 at 20:15