'How to write a function that takes a list of column names of a DataFrame, reorders selected columns the left and preserves unselected columns

I'd like to build a function

def reorderColumns(columnNames: List[String]) = ...

that can be applied to a Spark DataFrame such that the columns specified in columnNames gets reordered to the left, and remaining columns (in any order) remain to the right.

Example: Given a df with the following 5 columns

| A | B | C | D | E

df.reorderColumns(["D","B","A"]) returns a df with columns ordered like so:

| D | B | A | C | E



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source