Hello Programmers,

is it possible to create new 1D array from 2D array?
for example from this array

String[][] ArrVal= {
{"rec", "02"},
{"proc", "03"},
{"hscode", "10"},
{"sitc", "21"}};

take first column of ArrVal[0] and make this as new array with ArrVal[1] as value of new array, for example :
String[] rec = {"02"}
String[] proc = {"03"}
String[] hscode = {"10"}
String[] sitc = {"21"}

Dani AI

Generated

Short answer: yes — but avoid creating one compile-time variable per key at runtime. Treat each row as a key/value pair and either (A) extract two parallel 1D arrays (keys and values) or (B) convert the pairs into a Map for direct lookup. As pointed out, iteration is the core step; as suggested, a HashMap is a natural fit. ’s example rows map neatly to either approach.

Example — extract two parallel arrays:

String[] keys = new String[arr.length];
String[] values = new String[arr.length];
for (int i = 0; i < arr.length; i++) {
    String[] row = arr[i];
    if (row != null && row.length >= 2) {
        keys[i] = row[0];
        values[i] = row[1];
    }
}

Example — build a Map (recommended for lookups):

Map<String,String> map = new HashMap<>();
for (String[] row : arr) {
    if (row != null && row.length >= 2) {
        map.put(row[0], row[1]); // later values overwrite earlier ones for duplicate keys
    }
}
// single-element array for a key (if you really need an array object)
String[] single = new String[] { map.get("someKey") };

Notes and troubleshooting:

  • You cannot dynamically create new Java source variables at runtime — use a Map instead.
  • If key order matters, use LinkedHashMap. If keys can repeat and you need all values, use Map<String,List<String>> (or computeIfAbsent + add).
  • Always null-check rows and row length to avoid IndexOutOfBounds.
  • Creating many separate variables by hand is fragile; maps or parallel arrays scale and are clearer.

Recommended Answers

All 2 Replies

is it possible to create new 1D array from 2D array?

yes

How to create new array from array 2D member?

iterate over the 2d array and save the desired values from the 2d array to the new array

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.