Quelle est la façon la plus simple d'imprimer un tableau Java?

en Java, les tableaux ne remplacent pas toString() , donc si vous essayez d'en imprimer un directement, vous obtenez le nom de classe + @ + l'hexagone du hashCode du tableau, tel que défini par Object.toString() :

int[] intArray = new int[] {1, 2, 3, 4, 5};
System.out.println(intArray);     // prints something like '[I@3343c8b3'

mais en général, nous voulons plutôt quelque chose comme [1, 2, 3, 4, 5] . Quelle est la façon la plus simple de le faire? Voici quelques exemples d'entrées et de sorties:

// array of primitives:
int[] intArray = new int[] {1, 2, 3, 4, 5};
//output: [1, 2, 3, 4, 5]

// array of object references:
String[] strArray = new String[] {"John", "Mary", "Bob"};
//output: [John, Mary, Bob]
1581
demandé sur Md. Abu Nafee Ibna Zahid 2009-01-03 23:39:39

30 réponses

depuis Java 5, vous pouvez utiliser Arrays.toString(arr) ou Arrays.deepToString(arr) pour les tableaux à l'intérieur des tableaux. Notez que la version Object[] appelle .toString() sur chaque objet du tableau. La sortie est même décorée de la manière exacte que vous demandez.

exemples:

Tableau Simple:

String[] array = new String[] {"John", "Mary", "Bob"};
System.out.println(Arrays.toString(array));

sortie:

[John, Mary, Bob]

Réseau Imbriqué:

String[][] deepArray = new String[][] {{"John", "Mary"}, {"Alice", "Bob"}};
System.out.println(Arrays.toString(deepArray));
//output: [[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922]
System.out.println(Arrays.deepToString(deepArray));

sortie:

[[John, Mary], [Alice, Bob]]

double Tableau:

double[] doubleArray = { 7.0, 9.0, 5.0, 1.0, 3.0 };
System.out.println(Arrays.toString(doubleArray));

sortie:

[7.0, 9.0, 5.0, 1.0, 3.0 ]

int Tableau:

int[] intArray = { 7, 9, 5, 1, 3 };
System.out.println(Arrays.toString(intArray));

sortie:

[7, 9, 5, 1, 3 ]
2102
répondu RAnders00 2017-11-22 20:33:15

vérifiez toujours les bibliothèques standards en premier. Essayez:

System.out.println(Arrays.toString(array));

ou si votre tableau contient d'autres tableaux comme éléments:

System.out.println(Arrays.deepToString(array));
313
répondu Limbic System 2009-02-13 22:50:47

c'est agréable à savoir, cependant, comme pour "toujours vérifier les bibliothèques standard d'abord" je n'aurais jamais trébuché sur le tour de Arrays.toString( myarray )

-- puisque je me concentrais sur le type de myarray pour voir comment faire ceci. Je ne voulais pas avoir à répéter à travers la chose: je voulais un appel facile pour la faire sortir similaire à ce que je vois dans le débogueur Eclipse et myarray.toString() ne le faisait tout simplement pas.

import java.util.Arrays;
.
.
.
System.out.println( Arrays.toString( myarray ) );
87
répondu Russ Bateman 2010-11-29 14:05:59

dans JDK1.8 Vous pouvez utiliser les opérations agrégées et une expression lambda:

String[] strArray = new String[] {"John", "Mary", "Bob"};

// #1
Arrays.asList(strArray).stream().forEach(s -> System.out.println(s));

// #2
Stream.of(strArray).forEach(System.out::println);

// #3
Arrays.stream(strArray).forEach(System.out::println);

/* output:
John
Mary
Bob
*/
71
répondu Eric Baker 2016-03-27 20:22:16

si vous utilisez Java 1.4, vous pouvez à la place faire:

System.out.println(Arrays.asList(array));

(cela fonctionne aussi en 1.5+, bien sûr.)

38
répondu Ross 2009-01-03 21:44:05

à partir de Java 8, on pourrait aussi profiter de la méthode join() fournie par la String class pour imprimer des éléments de tableaux, sans les crochets, et séparés par un délimiteur de choix (qui est le caractère d'espace pour l'exemple ci-dessous):

String[] greeting = {"Hey", "there", "amigo!"};
String delimiter = " ";
String.join(delimiter, greeting) 

La sortie sera "Hé là amigo!".

35
répondu laylaylom 2015-12-23 18:51:48

Arrays.deepToString(arr) n'imprime que sur une ligne.

int[][] table = new int[2][2];

pour obtenir réellement une table à imprimer comme une table bidimensionnelle, je devais faire ceci:

System.out.println(Arrays.deepToString(table).replaceAll("],", "]," + System.getProperty("line.separator")));

il semble que la méthode Arrays.deepToString(arr) devrait prendre une chaîne de séparateur, mais malheureusement elle ne le fait pas.

27
répondu Rhyous 2015-05-14 23:40:47

tableaux.toString

comme réponse directe, la solution fournie par plusieurs, dont @Esko , en utilisant les méthodes Arrays.toString et Arrays.deepToString , est tout simplement la meilleure.

Java 8-Stream.collecter(joindre()), cours d'eau.forEach

ci - dessous, j'essaie d'énumérer quelques-unes des autres méthodes suggérées, en essayant d'améliorer un peu, avec le plus l'ajout notable étant l'utilisation de l'opérateur Stream.collect , en utilisant un joining Collector , pour imiter ce que fait le String.join .

int[] ints = new int[] {1, 2, 3, 4, 5};
System.out.println(IntStream.of(ints).mapToObj(Integer::toString).collect(Collectors.joining(", ")));
System.out.println(IntStream.of(ints).boxed().map(Object::toString).collect(Collectors.joining(", ")));
System.out.println(Arrays.toString(ints));

String[] strs = new String[] {"John", "Mary", "Bob"};
System.out.println(Stream.of(strs).collect(Collectors.joining(", ")));
System.out.println(String.join(", ", strs));
System.out.println(Arrays.toString(strs));

DayOfWeek [] days = { FRIDAY, MONDAY, TUESDAY };
System.out.println(Stream.of(days).map(Object::toString).collect(Collectors.joining(", ")));
System.out.println(Arrays.toString(days));

// These options are not the same as each item is printed on a new line:
IntStream.of(ints).forEach(System.out::println);
Stream.of(strs).forEach(System.out::println);
Stream.of(days).forEach(System.out::println);
27
répondu YoYo 2017-05-23 11:47:29

avant Java 8, nous aurions pu utiliser Arrays.toString(array) pour imprimer des tableaux unidimensionnels et Arrays.deepToString(array) pour des tableaux multidimensionnels. Nous avons l'option Stream et lambda en Java 8 qui peut également être utilisé pour l'impression du tableau.

Impression d'Un Tableau multidimensionnel:

public static void main(String[] args) {
    int[] intArray = new int[] {1, 2, 3, 4, 5};
    String[] strArray = new String[] {"John", "Mary", "Bob"};

    //Prior to Java 8
    System.out.println(Arrays.toString(intArray));
    System.out.println(Arrays.toString(strArray));

    // In Java 8 we have lambda expressions
    Arrays.stream(intArray).forEach(System.out::println);
    Arrays.stream(strArray).forEach(System.out::println);
}

la sortie est:

[1, 2, 3, 4, 5]

[Jean, Marie, Bob]

1

2

3

4

5

John

Mary

Bob

Impression d'un Tableau Multi-dimensionnel Juste au cas où nous voulons imprimer tableau multidimensionnel, nous pouvons utiliser Arrays.deepToString(array) comme:

public static void main(String[] args) {
    int[][] int2DArray = new int[][] { {11, 12}, { 21, 22}, {31, 32, 33} };
    String[][] str2DArray = new String[][]{ {"John", "Bravo"} , {"Mary", "Lee"}, {"Bob", "Johnson"} };

    //Prior to Java 8
    System.out.println(Arrays.deepToString(int2DArray));
    System.out.println(Arrays.deepToString(str2DArray));

    // In Java 8 we have lambda expressions
    Arrays.stream(int2DArray).flatMapToInt(x -> Arrays.stream(x)).forEach(System.out::println);
    Arrays.stream(str2DArray).flatMap(x -> Arrays.stream(x)).forEach(System.out::println);
} 

maintenant le point à observer est que la méthode Arrays.stream(T[]) , qui dans le cas de int[] nous renvoie Stream<int[]> et ensuite la méthode flatMapToInt() cartographie chaque élément de flux avec le contenu d'un flux cartographié produit en appliquant la fonction cartographique fournie à chaque élément.

la sortie est:

[[11, 12], [21, 22], [31, 32, 33]]

[[Jean, Bravo], [De Marie, Lee], [Bob, Johnson]]

11

12

21

22

31

32

33

John

Bravo

Mary

Lee

Bob

Johnson

23
répondu i_am_zero 2015-10-21 22:22:21
for(int n: someArray) {
    System.out.println(n+" ");
}
18
répondu somedude 2014-10-29 10:24:51

différentes façons D'imprimer des tableaux en Java:

  1. Façon Simple

    List<String> list = new ArrayList<String>();
    list.add("One");
    list.add("Two");
    list.add("Three");
    list.add("Four");
    // Print the list in console
    System.out.println(list);
    

sortie: [Un, Deux, Trois, Quatre]

  1. utilisant toString()

    String[] array = new String[] { "One", "Two", "Three", "Four" };
    System.out.println(Arrays.toString(array));
    

Sortie: [Un, Deux, Trois, Quatre]

  1. Impression de Tableau de Tableaux

    String[] arr1 = new String[] { "Fifth", "Sixth" };
    String[] arr2 = new String[] { "Seventh", "Eight" };
    String[][] arrayOfArray = new String[][] { arr1, arr2 };
    System.out.println(arrayOfArray);
    System.out.println(Arrays.toString(arrayOfArray));
    System.out.println(Arrays.deepToString(arrayOfArray));
    

Sortie: [[Ljava.lang.String;@1ad086a [[Ljava.lang.String;@10385c1, [Ljava.lang.Chaîne;@42719c] [[Cinquième, Sixième], [Septième, Huitième]]

"151940920 Resource": Accéder À Un Tableau

17
répondu Aftab Virtual 2016-11-15 17:05:20

utilisant la boucle pour est le moyen le plus simple d'imprimer un tableau à mon avis. Ici vous avez un exemple de code basé sur votre intArray

for (int i = 0; i < intArray.length; i++) {
   System.out.print(intArray[i] + ", ");
}

il donne la sortie comme la vôtre 1, 2, 3, 4, 5

12
répondu Andrew_Dublin 2013-12-27 23:31:15

je suis tombé sur ce post dans vanille #Java récemment. Il n'est pas très commode d'écrire Arrays.toString(arr); , puis d'importer java.util.Arrays; tout le temps.

veuillez noter qu'il ne s'agit pas d'une fixation permanente. Juste un hack qui peut rendre le débogage plus simple.

L'impression d'un tableau donne directement la représentation interne et le hashCode. Maintenant, toutes les classes ont Object comme parent-type. Alors, pourquoi ne pas pirater le Object.toString() ? Sans modification, la classe objet ressemble à ceci:

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

Que faire si cela est changé en:

public String toString() {
    if (this instanceof boolean[])
        return Arrays.toString((boolean[]) this);
    if (this instanceof byte[])
        return Arrays.toString((byte[]) this);
    if (this instanceof short[])
        return Arrays.toString((short[]) this);
    if (this instanceof char[])
        return Arrays.toString((char[]) this);
    if (this instanceof int[])
        return Arrays.toString((int[]) this);
    if (this instanceof long[])
        return Arrays.toString((long[]) this);
    if (this instanceof float[])
        return Arrays.toString((float[]) this);
    if (this instanceof double[])
        return Arrays.toString((double[]) this);
    if (this instanceof Object[])
        return Arrays.deepToString((Object[]) this);
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

cette classe moddée peut simplement être ajoutée au chemin de classe en ajoutant ce qui suit à la ligne de commande: -Xbootclasspath/p:target/classes .

maintenant, avec la disponibilité de deepToString(..) depuis Java 5, le toString(..) peut facilement être changé en deepToString(..) pour ajouter le support pour les tableaux qui contiennent d'autres tableaux.

j'ai trouvé que c'était un hack très utile et ce serait génial si Java pouvait simplement ajouter ceci. Je comprends les problèmes potentiels d'avoir des tableaux très grands puisque les représentations de chaîne pourraient être problématiques. Peut-être passer quelque chose comme un System.out ou un PrintWriter pour de telles éventualités.

8
répondu Debosmit Ray 2016-03-11 11:50:38

il doit toujours fonctionner quelle que soit la version JDK que vous utilisez:

System.out.println(Arrays.asList(array));

il fonctionnera si le Array contient des objets. Si le Array contient des types primitifs, vous pouvez utiliser des classes wrapper au lieu de stocker la primitive directement sous..

exemple:

int[] a = new int[]{1,2,3,4,5};

remplacer par:

Integer[] a = new Integer[]{1,2,3,4,5};

mise à jour:

Oui ! c'est à notez que convertir un tableau en tableau objet ou utiliser le tableau de L'objet est coûteux et peut ralentir l'exécution. cela se produit par la nature de java appelé autoboxing.

donc seulement pour l'impression, il ne doit pas être utilisé. nous pouvons faire une fonction qui prend un tableau comme paramètre et imprime le format désiré comme

public void printArray(int [] a){
        //write printing code
} 
7
répondu Girish Kumar 2016-05-13 11:52:23

en java 8, c'est facile. il y a deux mots clés

  1. flux": Arrays.stream(intArray).forEach
  2. méthode référence: ::println

    int[] intArray = new int[] {1, 2, 3, 4, 5};
    Arrays.stream(intArray).forEach(System.out::println);
    

si vous voulez imprimer tous les éléments dans le tableau dans la même ligne, alors il suffit d'utiliser print au lieu de println i.e.

int[] intArray = new int[] {1, 2, 3, 4, 5};
Arrays.stream(intArray).forEach(System.out::print);

une Autre façon, sans référence à une méthode utilisez simplement:

int[] intArray = new int[] {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(intArray));
7
répondu suatCoskun 2016-09-27 09:46:23

il y a une façon supplémentaire si votre tableau est de type char []:

char A[] = {'a', 'b', 'c'}; 

System.out.println(A); // no other arguments

imprime

abc
5
répondu Roam 2014-04-29 07:34:31

pour ajouter à toutes les réponses, l'impression de l'objet sous forme de chaîne JSON est également une option.

Utilisant Jackson:

ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
System.out.println(ow.writeValueAsString(anyArray));

Utilisant Gson:

Gson gson = new Gson();
System.out.println(gson.toJson(anyArray));
4
répondu Jean Logeart 2014-11-12 13:38:24

voici un raccourci simplifié que j'ai essayé:

    int x[] = {1,2,3};
    String printableText = Arrays.toString(x).replaceAll("[\[\]]", "").replaceAll(", ", "\n");
    System.out.println(printableText);

Il va imprimer

1
2
3

pas de boucles nécessaires dans cette approche et il est préférable pour les petits tableaux seulement

4
répondu Mohamed Idris 2015-02-21 07:12:25

vous pouvez boucler la boucle à travers le tableau, en imprimant chaque élément, que vous bouclez. Par exemple:

String[] items = {"item 1", "item 2", "item 3"};

for(int i = 0; i < items.length; i++) {

    System.out.println(items[i]);

}

sortie:

item 1
item 2
item 3
4
répondu Dylan Black 2016-07-20 23:55:49

il y a une façon suivante d'imprimer le tableau

 // 1) toString()  
    int[] arrayInt = new int[] {10, 20, 30, 40, 50};  
    System.out.println(Arrays.toString(arrayInt));

// 2 for loop()
    for (int number : arrayInt) {
        System.out.println(number);
    }

// 3 for each()
    for(int x: arrayInt){
         System.out.println(x);
     }
4
répondu Ravi Patel 2018-05-08 12:43:03
public class printer {

    public static void main(String[] args) {
        String a[] = new String[4];
        Scanner sc = new Scanner(System.in);
        System.out.println("enter the data");
        for (int i = 0; i < 4; i++) {
            a[i] = sc.nextLine();
        }
        System.out.println("the entered data is");
        for (String i : a) {
            System.out.println(i);
        }
      }
    }
3
répondu SamTebbs33 2015-04-05 20:30:48

à l'Aide de org.Apache.commun.lang3.StringUtils.les méthodes join(*) peuvent être une option

Par exemple:

String[] strArray = new String[] { "John", "Mary", "Bob" };
String arrayAsCSV = StringUtils.join(strArray, " , ");
System.out.printf("[%s]", arrayAsCSV);
//output: [John , Mary , Bob]

j'ai utilisé la dépendance suivante

<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
3
répondu Haim Raman 2015-08-08 20:18:14

pour-chaque boucle peut également être utilisé pour imprimer des éléments de tableau:

int array[] = {1, 2, 3, 4, 5};
for (int i:array)
    System.out.println(i);
3
répondu hasham.98 2018-03-11 19:23:36

ceci est marqué comme un duplicata pour impression d'un octet [] . Note: pour un tableau byte il y a des méthodes supplémentaires qui peuvent être appropriées.

vous pouvez l'imprimer comme une chaîne de caractères si elle contient des caractères ISO-8859-1.

String s = new String(bytes, StandardChars.ISO_8559);
System.out.println(s);
// to reverse
byte[] bytes2 = s.getBytes(StandardChars.ISO_8559);

ou si elle contient une chaîne UTF-8

String s = new String(bytes, StandardChars.UTF_8);
System.out.println(s);
// to reverse
byte[] bytes2 = s.getBytes(StandardChars.UTF_8);

ou si vous voulez l'imprimer en format hexadécimal.

String s = DatatypeConverter.printHexBinary(bytes);
System.out.println(s);
// to reverse
byte[] bytes2 = DatatypeConverter.parseHexBinary(s);

ou si vous voulez l'imprimer en base64.

String s = DatatypeConverter.printBase64Binary(bytes);
System.out.println(s);
// to reverse
byte[] bytes2 = DatatypeConverter.parseBase64Binary(s);

ou si vous voulez imprimer un tableau de valeurs des octets signés

String s = Arrays.toString(bytes);
System.out.println(s);
// to reverse
String[] split = s.substring(1, s.length() - 1).split(", ");
byte[] bytes2 = new byte[split.length];
for (int i = 0; i < bytes2.length; i++)
    bytes2[i] = Byte.parseByte(split[i]);

ou si vous voulez imprimer un tableau de valeurs de octets non signés

String s = Arrays.toString(
               IntStream.range(0, bytes.length).map(i -> bytes[i] & 0xFF).toArray());
System.out.println(s);
// to reverse
String[] split = s.substring(1, s.length() - 1).split(", ");
byte[] bytes2 = new byte[split.length];
for (int i = 0; i < bytes2.length; i++)
    bytes2[i] = (byte) Integer.parseInt(split[i]); // might need a range check.
2
répondu Peter Lawrey 2018-06-22 19:26:51
// array of primitives:
int[] intArray = new int[] {1, 2, 3, 4, 5};

System.out.println(Arrays.toString(intArray));

output: [1, 2, 3, 4, 5]

// array of object references:
String[] strArray = new String[] {"John", "Mary", "Bob"};

System.out.println(Arrays.toString(strArray));

output: [John, Mary, Bob]
1
répondu fjnk 2018-03-16 01:44:40

en java 8:

Arrays.stream(myArray).forEach(System.out::println);
0
répondu Mehdi 2018-05-08 20:05:49

Il y a plusieurs façons d'imprimer un tableau d'éléments.Tout d'abord, je vais l'expliquer, qu'est ce qu'un tableau?..Array est une structure de données simple pour stocker des données..Lorsque vous définissez un tableau , attribuez un ensemble de blocs de mémoire auxiliaire en RAM.Ces blocs de mémoire sont pris une unité ..

Ok, je vais créer un tableau comme celui-ci,

class demo{
      public static void main(String a[]){

           int[] number={1,2,3,4,5};

           System.out.print(number);
      }
}

regardez maintenant la sortie,

enter image description here

vous pouvez voir une chaîne de caractères inconnue imprimée..comme je l'ai mentionné plus haut, l'adresse mémoire dont le tableau(number array) déclaré est imprimé.Si vous souhaitez afficher les éléments dans le tableau, vous pouvez utiliser "pour la boucle" , comme ceci..

class demo{
      public static void main(String a[]){

           int[] number={1,2,3,4,5};

           int i;

           for(i=0;i<number.length;i++){
                 System.out.print(number[i]+"  ");
           }
      }
}

regardez maintenant la sortie,

enter image description here

Ok,éléments imprimés avec succès d'un tableau de dimension..Maintenant, je vais vous envisagez un tableau en deux dimensions..Je vais déclarer deux tableaux de dimensions comme " number2 "et imprimer les éléments en utilisant" tableaux.deepToString()" mot-clé.Avant d'utiliser cela, vous devrez importer 'java.util.La bibliothèque des tableaux.

 import java.util.Arrays;

 class demo{
      public static void main(String a[]){

           int[][] number2={{1,2},{3,4},{5,6}};`

           System.out.print(Arrays.deepToString(number2));
      }
}

envisager la sortie,

enter image description here

en même temps , en utilisant deux pour les boucles ,les éléments 2D peuvent être imprimés..Je vous remercie !

0
répondu GT_hash 2018-07-01 15:45:41

si vous voulez imprimer, évaluer le contenu du tableau comme cela vous pouvez utiliser Arrays.toString

jshell> String[] names = {"ram","shyam"};
names ==> String[2] { "ram", "shyam" }

jshell> Arrays.toString(names);
 ==> "[ram, shyam]"

jshell> 
-1
répondu Sudip Bhandari 2018-07-06 12:29:41

vous pouvez utiliser Arrays.toString()

String[] array = { "a", "b", "c" };  
System.out.println(Arrays.toString(array));
-3
répondu Atuljssaten 2018-03-11 17:12:18

la façon La plus simple d'imprimer un tableau est d'utiliser une boucle for:

// initialize array
for(int i=0;i<array.length;i++)
{
    System.out.print(array[i] + " ");
}
-5
répondu Joy Kimaru 2017-12-29 20:12:25