How to put in a new array a vector without empty spaces

-1

First array

String datos[]={"hola", "", "como", "", "", "estas", ""};

Make an algorithm that skips empty spaces and that you in a new array

datos new[]={"hola", "como", "estas"};

in java please

This is what I have so far

String[] datosnew = new String[datos.length]; 
for (int i = 0; i < datos.length; i++) { 
  if (datos[i].equals("")) { 

  } 
} 
    
asked by Amadeuss96 15.01.2018 в 16:11
source

2 answers

0

Since you want datosnew to store the data of the non-blank positions ("") of the array datos , the size of the array datosnew must be 3, since that is the number of positions with data in the array datos . If you create the array datosnew with the same size as the array datos , at the end you will have the same number of positions, but instead of being empty ("") these would have the value of null , because if you create an array of type String and you do not fill its positions, the default value of these will be null.

Then, as you are doing, you go through the array datos with a cycle and with a conditional you evaluate if the positions are not empty (""). If the position is not empty, you store the data for that position in the array datosnew ; out of conditional you create a counter that increases its value each time the condition of the if is fulfilled, to store the data of the array datos in different positions of the array datosnew .

String datos[] = {"hola", "", "como", "", "", "estas", ""};
String[] datosnew = new String[3];
int j = 0; 
for (int i = 0; i < datos.length; i++) {

    if (!datos[i].equals("")) {
        datosnew[j] = datos[i];
        j++;
    } 
}
  

! is a boolean operator that inverts a boolean operation, if a boolean operation is true it becomes false and vice versa.

    
answered by 15.01.2018 / 16:27
source
0

In Java 8 you can do it with streams, simply filtering those that are empty:

import java.util.Arrays; 
import java.util.List; 
import java.util.stream.Collectors;

class Main {   
 public static void main(String[] args) {
    String datos[] = {"hola", "", "como", "", "", "estas", ""};
    List<String> datosFiltrados = Arrays.asList(datos).stream().filter(d -> !d.isEmpty()).collect(Collectors.toList());
    System.out.println(datosFiltrados);   
 } 
}

Will give you, as a result:

[hola, como, estas]

Code in use: link

In Java 8 the use of streams allows us to manipulate and process more easily the data sources, in this case, a list of strings. In the example, we use the stream() to go through the list; with the filter() method, we filter the list specifying an expression that validates if the data d is not empty (in case it is empty, ignores it) and the method collect() to return the resulting list.

This solution is cleaner and is perfect to start learning to use lists with streams. Greetings.

    
answered by 15.01.2018 в 17:23