2

I have a object list-

List<Object> sample = new ArrayList<Object>(); 

and it contain following values-

[This is an apple., Ram is a boy., What is your name?]. 

I want to modify it like this-

[{ "q": "This is an apple." }, { "q": "Ram is a boy" }, { "q": "What is your name?" }]

How to do it?

P.S - I am new to Java. Thanks for your help in advance.

2
  • Create a class with a qfield (that you should name much better), put instances of that class in a list. Make sure to use the right generic type for your list: List<MayNewClass>. Commented Sep 26, 2017 at 6:10
  • Do some search about Map in Java Commented Sep 26, 2017 at 6:10

3 Answers 3

3

You can do this by creating List of JSONObject as below:

List<JSONObject> yourList = new ArrayList<JSONObject>();
for(Object obj: sample) {
    JSONObject jsonObj = new JSONObject();
    jsonObj.put("q",(String)obj);
    yourList.add(jsonObj);
}

Above code will create a new list with name yourList with required format of data.

Sign up to request clarification or add additional context in comments.

Comments

2

You can use a custom model as :

class CustomObject {
   String q;
   ...getters, setters etc 
}

and use further it as

List<CustomObject> = new ArrayList<CustomObject>();

Comments

0

Here is if you are on jdk8 or later:

import java.util.*;
import java.util.stream.*;

public class HelloWorld{

 public static void main(String []args){

    List<String> sample = new ArrayList<String>(Arrays.asList("This is an apple.", "Ram is a boy.", "What is your name?")); 
    System.out.println(sample);

   List<Map<String,String>> transformed = sample.stream()
            .map(p -> {Map<String,String> m = new HashMap<String,String>(); m.put("q",p); return m;})
            .collect(Collectors.toList());

     System.out.println(transformed);
 }
}

Edit: Instead of List<Map<String,String>> transformed , you can also use Map.Entry<String,String> as well as it's just key-value pair you want in your list.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.