Saman1154
Saman1154

Reputation: 137

Delete part of element in Java String array

I want to take input from user in String array. Delete few parts of it and print it out in different text area block.

For example:

Input in String array.

===========

Mr: Alex Simmons
Miss: Susan Kent
Mrs: J. Peterson

===========

I want the output to look something like this. After removing Mr:, Miss:, Mrs: rest of the values in a single line or element

===========
Alex Simmons Susan Kent J. Peterson

===========

Here is the code i am working with.

private void jButton18ActionPerformed(java.awt.event.ActionEvent evt) {
        String[] names = jTextArea11.getText().split("\\n");


        List<String> myList = new ArrayList<>(Arrays.asList(names));


        myList.remove("Mr:");
        myList.remove("Miss:");
        myList.remove("Mrs:");

        names = myList.toArray(new String[0]);

        jTextArea12.setText(Arrays.toString(names));
}

The above code isn't seems to be working out for me..

Output is:
[Mr: Alex Simmons, Miss: Susan Kent, Mrs: J. Peterson]

"[ ]" braces at the end and separated by "," is not what i had in mind. Also the remove() isn't seems to be working.

Upvotes: 2

Views: 2250

Answers (7)

Ousmane D.
Ousmane D.

Reputation: 56433

Currently, when you perform the three remove calls:

myList.remove("Mr:");
myList.remove("Miss:");
myList.remove("Mrs:");

You're essentially trying to "remove 'Mr:' , 'Miss:' and 'Mrs:' from myList if they exist" but this is not what you want, rather what you want is to "remove the said data from the elements inside myList.

You could accomplish this via a typical for loop but it might just be more convenient to use a stream here as you later need to join the result and set the jTextArea12 to it.

Thus, after splitting you can use a stream to achieve the said requirement:

String result = Arrays.stream(names)
          .map(s -> s.replace("Mr:", "").replace("Miss:", "").replace("Mrs:", ""))
          .collect(Collectors.joining(" "));

jTextArea12.setText(result);

full code:

private void jButton18ActionPerformed(java.awt.event.ActionEvent evt) {
     String[] names = jTextArea11.getText().split("\\n");

     String result = Arrays.stream(names)
              .map(s -> s.replace("Mr:", "")
                         .replace("Miss:", "").replace("Mrs:", ""))
              .collect(Collectors.joining(" "));

     jTextArea12.setText(result);
}

Upvotes: 0

notionquest
notionquest

Reputation: 39196

Another solution using substring. The advantage of this approach is that the title (Mr, Miss etc) is not hardcoded.

If the title is there, it will skip that part. Otherwise, it will take the full name (see 1Peterson value in list).

public static void main(String[] args) {
    List<String> stringList = new ArrayList<>();
    stringList.add("Mr: Alex Simmons");
    stringList.add("Miss: Susan Kent");
    stringList.add("Mrs: J. Peterson");
    stringList.add("1Peterson");

    List<String> outList = new ArrayList<>();

    for (String s : stringList) {
        outList.add(s.substring(s.indexOf(": ")+1));
    }

    System.out.println(outList);
}

Output:-

[ Alex Simmons, Susan Kent, J. Peterson, 1Peterson]

Upvotes: 0

Sandeepa
Sandeepa

Reputation: 3755

This will replace the Strings in the list with converted Strings and it will work for any number of Strings,

import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("Mr: Alex Simmons", "Miss: Susan Kent", "Mrs: J. Peterson", "Mr: Abc", "Miss: Cdf");
        for (int i = 0; i < list.size(); i++) {
            list.set(i, list.get(i).replace("Mr:", ""));
            list.set(i, list.get(i).replace("Miss:", ""));
            list.set(i, list.get(i).replace("Mrs:", ""));
        }
        System.out.println(list);
    }
}

Upvotes: 0

azro
azro

Reputation: 54148

You need to operate the changement on the elements, no on the list, like :

List<String> myList = new ArrayList<>(Arrays.asList(names));
List<String> res = new ArrayList<>();
for(String name : myList){
    res.add(name.replaceAll("((Mr:|Miss:|Mrs:)\\s)", "");
}

str = String.join(", ", res);
jTextArea12.setText(str);

You can also use Stream operation and goes directly to the String without passing to en array:

List<String> myList = new ArrayList<>(Arrays.asList(names));
String str = myList.stream()
                   .map(name -> name.replaceAll("((Mr:|Miss:|Mrs:)\\s)", ""))
                   .collect(Collectors.joining(", "));
jTextArea12.setText(str);

Upvotes: 1

Kars
Kars

Reputation: 917

This is one way to do it using substring. This will paste all the names together without spaces.

    String[] names = {"Mr. Smith","Mrs. Smith","Ms. Smith"};

    String newString = "";

    for (int i = 0; i < names.length; i++) {
        if (names[i].substring(0, 3).equals("Mr.") || names[i].substring(0, 3).equals("Ms.")) {
            newString += names[i].substring(4);
        } else if (names[i].substring(0,4).equals("Mrs.")) {
            newString += names[i].substring(5);
        }
    }

Upvotes: 1

Sombriks
Sombriks

Reputation: 3622

If you use java 8 take a look at map function

myList = myList.stream().map(s -> 
s.replaceAll("Mr|Miss|Mrs:","")).collect(Collectors.toList())

Upvotes: 2

Rishi Saraf
Rishi Saraf

Reputation: 1812

Your code is incorrect. You are trying to remove element from list. Try below code. It will loopover your list. From each element it will replace desired string with empty string

 for (int i=0; i< myList.size();i++) {
      String newVal = myList.get(i).replace("Mr:", "").replace("Miss:", "").replace("Mrs:", "");
            myList.add(i,newVal);

}

Update: There is small correction. After replace we have to reset the replaces value in list

Upvotes: 3

Related Questions