Emraan Emraan - 18 days ago 8
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()))
.where(x("meta().id").like(s("PRODUCTOPTION%")).and(x("Status").eq(s("Ready"))));

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:

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


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

Thanks
Emraan

Answer

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){
                continue;
            }
            String result = "{" + resultPlanningIds[1];
            finalResult = finalResult.append(result + ",");
        }
        System.out.println(finalResult);

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.