1

I have the following dataframe :

+--------------------+
|    column          |
+--------------------+
| [99896, 10, ]      |     
|[50, 30, 40, ]      |
+--------------------+

Shema of column is :

 |-- column: array (nullable = true)
    |-- element: string (containsNull = true)

When I execute the following code :

for (Iterator<Row> iter = dataframee.toLocalIterator(); iter.hasNext();){
        String item = (iter.next()).get(0).toString();
        System.out.println(item);
    }

I get the following output :

WrappedArray(99896, 10, )
WrappedArray(50, 30, 40, )

How can I convert this output to String like :

[99896, 10,50,30,40 ]    

I need your help .

Thank you

2 Answers 2

2

Try this-

Load the test data provided

  Dataset<Row> df = spark.sql("select column from values array(99896, 10, null), array(50, 30, 40, null) T(column)");
        df.show(false);
        df.printSchema();
        /**
         * +-------------+
         * |column       |
         * +-------------+
         * |[99896, 10,] |
         * |[50, 30, 40,]|
         * +-------------+
         *
         * root
         *  |-- column: array (nullable = false)
         *  |    |-- element: integer (containsNull = true)
         */

Option-1


      StringBuilder sb = new StringBuilder();
        sb.append("[");
        for (java.util.Iterator<Row> iter = df.toLocalIterator(); iter.hasNext();){
            String item = (iter.next()).getList(0).stream()
                    .filter(Objects::nonNull)
                    .map(String::valueOf)
                    .collect(Collectors.joining(","));
            sb.append(item).append(",");
        }
        int i = sb.lastIndexOf(",");
        sb.replace(i, i+1, "]");
        System.out.println(sb);
        /**
         * [99896,10,50,30,40]
         */

option-2


         Dataset<Row> p = df.withColumn("column",
                expr("concat('[', concat_ws(',', collect_list(concat_ws(',', column))), ']')"));
        for (java.util.Iterator<Row> iter = p.toLocalIterator(); iter.hasNext();){
            String item = (iter.next()).get(0).toString();
            System.out.println(item);
        }
        /**
         * [99896,10,50,30,40]
         */

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

Comments

2

So basically, what you're doing is looping through each row, getting the WrappedArray for that row and using WrappedArray's toString() method. What you need to do instead of calling toString() is to loop over that WrappedArray and print each value in it

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.