I have a list of data like the one given below:
List<Data> data = new ArrayList<Data>(); data.add(new Data("d1", "option1")); data.add(new Data("d2", "option1")); data.add(new Data("d1", "option2")); data.add(new Data("d3", "option1")); data.add(new Data("d3", "option2")); data.add(new Data("d3", "option3")); The structure looks like this:
class Data { private String name; private String option; private List<String> options = new ArrayList<>(); public Data(String name, String option) { this.name = name; this.option = option; } public void addOption(String option) { options.add(option); } } How to group the items to a new array based on the name with its options,
[ "d1": { "name": "d1", "options": ["option1", "option2"] }, "d2": { "name": "d2", "options": ["option1"] }, "d3": { "name": "d3", "options": ["option1", "option2", "option3"] } ]
optionfields in theoptionsfield of a new instance ofData? For the latter I would already recommend to change something because it's weird to have both a list of options and a single String option in your class if they both basically mean the same.List; it's an interface. Why doesDatahave both a singleoptionand a list ofoptions? You never calladdOption. Also, you can't group them to an array. Do you mean aMap?