java - Properties file to map in Spring 6 - Stack Overflow

admin2025-04-25  2

I have a Prop file like this

abc.name = John
abc.id = 1234
abc.dep = sales

bac.name = Jen
bac.id = 3422
bac.dep = marketing

Now I need to convert it to a map where keys will be abc, bac and the value would be a object which has the 3 fields, name, id and dep.

public class Identity{
   private String name;
   private Long id;
   private dep;
}

The map I want to create is HashMap<String, Identity>(). I have done this by reading the Prop file and iterate over the map the, split the keys and did computeIfAbsent then a switch statement for mapping the name, id and dep.

Is there any easier and cleaner way to do it. Is there any library present which can perform this.

I have a Prop file like this

abc.name = John
abc.id = 1234
abc.dep = sales

bac.name = Jen
bac.id = 3422
bac.dep = marketing

Now I need to convert it to a map where keys will be abc, bac and the value would be a object which has the 3 fields, name, id and dep.

public class Identity{
   private String name;
   private Long id;
   private dep;
}

The map I want to create is HashMap<String, Identity>(). I have done this by reading the Prop file and iterate over the map the, split the keys and did computeIfAbsent then a switch statement for mapping the name, id and dep.

Is there any easier and cleaner way to do it. Is there any library present which can perform this.

Share Improve this question asked Jan 16 at 11:28 Rajib SharmaRajib Sharma 581 silver badge7 bronze badges 3
  • Straightforward is JAXB with annotations where you would replace the prop file with XML. If you want well-defined data, writing data too. – Joop Eggen Commented Jan 16 at 11:45
  • 1 Don't forget Properties is already essentially a Map so, for variable props of type Properties, you could do something like the following: Map<String, Identity> identities = new TreeMap<>();for (Iterator<Map.Entry<Object, Object>> i = new TreeMap<>(props).entrySet().iterator();i.hasNext();) {var e = i.next();String key = e.getKey().toString().replaceAll("\\..*", "");identities.put(key, new Identity(e.getValue().toString(),Long.valueOf(i.next().getValue().toString()), i.next().getValue().toString()));} – g00se Commented Jan 16 at 12:29
  • 1 Thanks for the reply. I have achieved this by splitting the key. I was wondering if there are any library like snakeyml, where we can achieve this without writing all the iteration setter and toString – Rajib Sharma Commented Jan 16 at 13:22
Add a comment  | 

1 Answer 1

Reset to default 0

I used Snake YML to resolve this. I have to change the prop file to YML file and read it through snake yml. the used ObjectMapper to convert it to Map<String, Identity>

转载请注明原文地址:http://anycun.com/QandA/1745534783a90886.html