Home > Software engineering >  Remove column from 2D Array in Java
Remove column from 2D Array in Java

Time:11-23

I have a 2D String Array in java where i is rows and j is cols.

I'm looking for an elegant solution to remove cols in the following array.

String[i][j] data; 

The columns provided can either be a single column or more than one column i.e. if the columns to be removed are (7,8) then all values on data[i][7] and data [i][8] should be removed from the array.

I tried various solutions such as declaring a new array and copying from the previous array excluding the columns but I'm wondering if there's a more elegant solution I can use. Any leads?

CodePudding user response:

I took pity on you and wrote this. I think this is what "elegant" looks like in Java?

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

class ArrayMangler {
    public static void main(String[] args) {
        String[] sample1 = {"Adam", "Bob", "Charlie", "Donald"};
        String[] sample2 = {"Ernst", "Ferdinand", "Godfrey", "Hrothgar"};
        String[] sample3 = {"Iago", "Jormangandr", "Killroy", "Lorelei"};
        String[][] input = {sample1, sample2, sample3};
        
        List<Integer> badIndexes = Arrays.asList(1, 3);
        String[][] output = removeColumns(input, badIndexes);
        for (String[] row : output){
            System.out.println(Arrays.toString(row));
        }
        
    }
    public static String[][] removeColumns(String[][] input, List<Integer> indexesToTrim){
        return Arrays.stream(input)
            .map(arr -> removeFromRow(arr, indexesToTrim))
            .toArray(String[][]::new);
    }
    public static String[] removeFromRow(String[] input, List<Integer> indexesToTrim){
        return IntStream
            .range(0,input.length)
            .filter(i ->!indexesToTrim.contains(i))
            .mapToObj(i -> input[i])
            .toArray(String[]::new);
    }
}
  • Related