Emraan Emraan - 1 year ago 106
Java Question

Query a part of string from an ArrayList

I have the below couchbase query in Java to get an array list of a particular value.

Statement statement = select("PlanningId").from(i(CouchbaseBucket.RangePlan.toString()))

String[] planningIDs = couchbaseRepository.getQueryResult(bucket, statement);

This return the output as:

[{"PlanningId":"PRODUCTPLANNING_666"}, {"PlanningId":"PRODUCTPLANNING_777"}]

I need the output with only the values:


I am not able to get this using the substring or a split.
How would I achieve this?


Answer Source

Like mentioned in the comments, on each query if the returned result contains a single String like: {"PlanningId":"PRODUCTPLANNING_666"}, {"PlanningId":"PRODUCTPLANNING_777"},...., the process to extract only the required part of {"PRODUCTPLANNING_XXX"},... can be done as follows:

Say you have a String like

String planningIds = {"PlanningId":"PRODUCTPLANNING_666"}, {"PlanningId":"PRODUCTPLANNING_777"},....{"PlanningId":"PRODUCTPLANNING_NNN"}

and if you want to capture each {"PRODUCTPLANNING_XXX} in a single String,

StringBuilder finalResult = new StringBuilder();
        String[] results = allPlanningIds.split(",");
        for(String eachPlanningId : results){
            String[] resultPlanningIds = eachPlanningId.split(":");
            if(resultPlanningIds.length != 2){
            String result = "{" + resultPlanningIds[1];
            finalResult = finalResult.append(result + ",");

or if you want to capture each {"PRODUCTPLANNING_XXX} as seperate String objects within an ArrayList, in the above code snippet, change StringBuilder finalResult = new StringBuilder(); to List<String> finalResults = new ArrayList<>(); and

finalResult = finalResult.append(result + ","); to finalResults.add(result).

I hope this is what you were looking for.

Note: Please check the end / null conditions of the String[] results array.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download