javaarraylistreplaceallremoveall

Need to figure out how to replace the comma in the array list for a space


I have tried to use replaceAll and removeAll but still can't change the list without commas. I tried to add after list + ""); but nothing changed. Still get the output with commas. I need to remove the commas in the output. Need only one white space between numbers. (See at the end the output)

(Remove duplicates) Write a method that removes the duplicate elements from an array list of integers using the following header:
public static void removeDuplicate(ArrayList<Integer> list)
Write a test program that prompts the user to enter 10 integers to a list and displays the distinct integers separated by exactly one space.

package exercise11_13;

import java.util.ArrayList;
import java.util.Scanner;

public class Exercise11_13 {

    /**
     * @param args the command line arguments
     */
    // Main method
    public static void main(String[] args) {
        // Create de Scanner object.
        Scanner input = new Scanner(System.in);
        
        // Prompt the user to enter ten integer numbers. 
        System.out.print("Please, enter ten (10) integers numbers: ");
        
        // Create the ListArray (List object).
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) list.add(input.nextInt());

        removeDuplicate(list);
        
        System.out.println("Display the distinct integers in their input order "
                + "and seperated by exactly one space: " + "\n" + list );
    }

    public static void removeDuplicate(ArrayList<Integer> list) {

        ArrayList<Integer> temp = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {

            if (!temp.contains(list.get(i))) {
                temp.add(list.get(i));
            }
        }
        list.clear();
        list.addAll(temp);
        
    }
}

Output: I need to remove the commas in the output. Need only one white space between numbers. run:

Please, enter ten (10) integers numbers: 78
99
54
63
56
78
63
14
67
99
Display the distinct integers in their input order and seperated by exactly one space: 
[78, 99, 54, 63, 56, 14, 67]
BUILD SUCCESSFUL (total time: 27 seconds)

Solution

  • As the question is tagged with replaceAll, it is indeed possible to remove all "redundant" characters supplied by List::toString method (brackets and commas) using a regular expression [,\[\]] (brackets should be escaped with \):

    List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
    System.out.println(list.toString().replaceAll("[,\\[\\]]", "")); // 1 2 3 4 5
    

    Or, knowing that the brackets are the first and the last characters, they can be removed with the help of substring and then apply String::replace:

    String str = list.toString();
        
    System.out.println(str.substring(1, str.length() - 1).replace(",", "")); // 1 2 3 4 5