0

I have 3 generic arrays which all have a pre-determined size of 25. For example, if its only 5 actual values in the array, it will display those 5, than the next 20 as null. I dont want to display any null values. Do I edit something in the toString? My toString is

public String toString(){
  return Arrays.toString(container);
}

Container being an array object created from a constructor function. Here is what my output looks like..

Picture of output

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69
Riddler
  • 1
  • 1
  • Please import the result in your post, don't use external link. – Jean-Baptiste Yunès Feb 13 '19 at 15:29
  • 1
    I don't understand how taking and uploading a photo of your screen seems to be easier than copy/pasting that one line of text into the question. – f1sh Feb 13 '19 at 15:31
  • https://stackoverflow.com/questions/26353491/print-only-certain-elements-in-an-array? – achAmháin Feb 13 '19 at 15:31
  • 1
    It's unclear what a "generic array" is. Do you mean an array whose element type is given by a type variable? Or perhaps simply an explicit `Object[]`? – John Bollinger Feb 13 '19 at 15:33
  • Sounds like a poor datamodel to me. Either use `ArrayList` instead of array or keep a top pointer to the first vacant slot so you know which part of the array to print. Then there are a number of options for printing. – Ole V.V. Feb 13 '19 at 15:34

4 Answers4

2

In the following, I suppose your container is something like Something []container.

Pre-java 8 using StringBuilder:

public String toString(){
    StringBuilder s = new StringBuilder();
    for (Something i : container) if (i!=null) s.append(i.toString()+",");
    return s.toString();
}

Post-java 8 using streams:

public String toString(){
    return Arrays.stream(container)
                 .filter(Objects::nonNull)
                 .map(Object::toString)
                 .collect(Collectors.joining(","));
}
Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69
2

The Arrays.toString() methods all produce a representation of the whole array. If that's not what you want, then you need to choose a different approach. For example, you might do something like this:

String result = Arrays.stream(container)
        .filter(Objects::nonNull)
        .map(Objects::toString)
        .collect(Collectors.joining(",", "[", "]"));
John Bollinger
  • 160,171
  • 8
  • 81
  • 157
1

Assuming you use java8 or later:

Arrays.toString(Arrays.stream(container).filter(i->i!=null).collect(Collectors.toList()));
f1sh
  • 11,489
  • 3
  • 25
  • 51
1

Another solution with java8 stream:

MyType[] array = Arrays.stream(originalArray)
                       .filter(Objects::nonNull)
                       .toArray(MyType[]::new);
    
System.out.println(Arrays.toString(array));
dreamcrash
  • 47,137
  • 25
  • 94
  • 117
dim
  • 992
  • 11
  • 26