Remove element in strings arraylist java [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Hi am new in using Java and I just placed a list of strings in an array list of which I would like to remove certain elements in each of the strings below
ArrayList<String> data = new ArrayList<String>();
data.add( "ksh10,000");
data.add( "ksh20,000");
data.add( "ksh30,000");
data.add( "ksh40,000");
data.add( "ksh50,000');
so I would like to remove the "ksh" and the comma in between the strings so as to get an out put like
10000,20000,30000,40000,50000
what i tried
for (int i = 0; i < data.lenght(); i++ ) {
data.set(i, data.get(i).replace("ksh", ""));
data.set(i, data.get(i).replace(",",""));
}
.Thanks in advance for your help.

If all you want to do is change the values put into data, loop through each element and use the replace method:
for (int i = 0; i < data.size(); i++ ) {
data.set(i, data.get(i).replace("ksh", ""));
data.set(i, data.get(i).replace(",",""));
}
This replaces "ksh" strings and commas with an empty string. as Snoob said, replace() only returns the new String, because Strings are immutable.

public class Main {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add( "ksh10,000");
list.add( "ksh20,000");
list.add( "ksh30,000");
list.add( "ksh40,000");
list.add( "ksh50,000");
printStrings(list);
ArrayList<String> newList = editList(list);
printStrings(newList);
}
public static ArrayList<String> editList(ArrayList<String> list){
ArrayList<String> newList = new ArrayList<>();
for(String str : list) {
String temp = "";
for(char c : str.toCharArray()) {
if(Character.isDigit(c))
temp += c;
}
newList.add(temp);
}
return newList;
}
public static void printStrings(ArrayList<String> list) {
for(String str : list){
System.out.println(str);
}
}
}
The best way to do this (if you don't know the exact structure of the string) is to check if a character is a digit and if so add it to the string, loop this for every string in the list and return a new list which contains the edited version of the strings in the first list.

This is a great change to use the Stream API. I'm going to leave one piece of the implementation up to you as an exercise.
import java.util.stream.*;
class Solution {
String generateOutput (ArrayList<String> inputValues) {
return data.stream()
.map(this::scrubValue)
.collect(Collectors.joining(","));
}
String scrubValue (String input) {
// you'll need to write code here that takes an input like "ksh10,000" and returns "10000"
}
}

I understand that you would only like to extract numbers from the ArrayList of String. so we can use a regex such as [^0-9] to remove all non-digits like below.
String number = stringData.replaceAll("[^0-9]", "");
here stringData is the string from which you want to extract only numbers.
Below is the loop.
for(int i=0; i<data.size(); i++){
data.set(i, data.get(i).replaceAll("[^0-9]", ""));
}
Hope it helps.

Related

Converting array list to a string array

I've been trying to convert my string array list to a string array so I can print it but have been unable to do so.
This is the class I have, randomQuestion which takes in an array list from the gameQuestions method in the same class.
I have never tried to convert an array list using a loop before hence the difficulty, I was able to convert it fine with the code
String[] questions = data1.toArray(new String[]{});
But I need it to loop through using a for loop to store it in an array which I can then print one at a time once a question is answered successfully.
The error I'm receiving from netbeans is cannot find symbol
Symbol:methodtoArray(String[]) for the .toArray portion below.
public String[] randomQuestion(ArrayList data1) {
Collections.shuffle(data1);
for (int question = 0; question < 10; question++) {
ranquestions = data1.get(question).toArray(new String[10]);
}
return ranquestions;
}
Any help would be greatly appreciated.
You can use List.toArray(). Class List has a method:
<T> T[] toArray(T[] a);
Assuming you have an ArrayList<String>, you can use String.join(delimiter, wordList) in order to concatenate all the elements to a single String:
public static void main(String[] args) {
// example list
List<String> words = new ArrayList<String>();
words.add("You");
words.add("can");
words.add("concatenate");
words.add("these");
words.add("Strings");
words.add("in");
words.add("one");
words.add("line");
// concatenate the elements delimited by a whitespace
String sentence = String.join(" ", words);
// print the result
System.out.println(sentence);
}
The result of this example is
You can concatenate these Strings in one line
So using your list, String.join(" ", data1) would create a String with the elements of data1 delimited by a whitespace.
The question is how to create an array with only 10 elements of the list, if I understood correctly.
Streams (Java 8):
String[] ranquestions = data1.stream()
.limit(10)
.toArray(String[]::new);
Loop (based on question, avoiding unnecessary changes):
String[] ranquestions = new String[10];
for(int question = 0; question < 10; question++) {
ranquestions[question] = data1.get(question);
}
always assuming List<String> data1, if not some conversion is needed.
Example:
String[] ranquestions = data1.stream()
.limit(10)
.map(String::valueOf)
.toArray(String[]::new);
or, loop case:
ranquestions[question] = String.valueOf(data1.get(question));
You can do:
private String[] randomQuestions(ArrayList data){
Collections.shuffle(data);
return (String[]) data.toArray();
}
If you are sure you are getting a list of string (question) you can instead
private String[] randomQuestions(List<String> data){
Collections.shuffle(data);
return (String[]) data.toArray();
}
Edit 1
private static String[] randomQuestions(ArrayList data){
Collections.shuffle(data);
String[] randomQuestions = new String[data.size()];
for(int i=0; i<data.size(); i++){
randomQuestions[i] = String.valueOf(data.get(i));
}
return randomQuestions;
}

Remove elements from ArrayList after finding element with specific char

I have an ArrayList that contains a number of Strings, I want to be able to iterate through the ArrayLists contents searching for a string containing a semicolon. When the semicolon is found I then want to delete all of the Strings including and after the semicolon string.
So;
this, is, an, arra;ylist, string
Would become:
this, is, an
I feel like this is a very simple thing to do but for some reason (probably tiredness) I can't figure out how to do it.
Here's my code so far
public String[] removeComments(String[] lineComponents)
{
ArrayList<String> list = new ArrayList<String>(Arrays.asList(lineComponents));
int index = 0;
int listLength = list.size();
for(String str : list)
{
if(str.contains(";"))
{
}
index++;
}
return lineComponents;
}
This becomes trivial with Java 9:
public String[] removeComments(String[] lineComponents) {
return Arrays.stream(lineComponents)
.takeWhile(s -> !s.contains(";"))
.toArray(String[]::new);
}
We simply form a Stream<String> from your String[] lineComponents and take elements until we find a semicolon. It automatically excludes the element with the semicolon and everything after it. Finally, we collect it to a String[].
First of all I think you are confusing arrays and arraylists. String[] is an array of strings while ArrayList<String> is an arraylist of strings. Take into account that those are not the same and you should read Array and ArrayList documentation if needed.
Then, to solve your problem following the ArrayList approach you can go as follows. Probably it's not the optimum way to do it but it will work.
public List<String> removeComments(List<String> lineComponents, CharSequence finding)
{
ArrayList<String> aux = new ArrayList<String>();
for(String str : lineComponents)
{
if(str.contains(finding))
break;
else
aux.add(str);
}
return aux;
}
This example is just for performance and bringing back my old favorite arraycopy:
public String[] removeComments(String[] lineComponents) {
int index = -1;
for (int i = 0; i < lineComponents.length; i++) {
if ( lineComponents[i].contains(";") ) {
index = i;
break;
}
}
if (index == -1) return lineComponents;
return Arrays.copyOf(lineComponents, index);
}

Remove String from list if certain character missing

I have a list of words ["home", "shop", "salmon", "time"] and I have a scrambled String "ahlowemr". I want to check if each word in the list has characters from this scrambled String and remove the word from list if it doesn't contain all the characters.
In this example, less "home", the remaining 3 Strings should be removed. I tried to loop as follows but it doesn't allow me to check characters. And I am nesting loops which I think is not a good idea. Is there any way around this?
ArrayList<String> myList = new ArrayList<String>();
myList.add("home");
myList.add("shop");
myList.add("salmon");
myList.add("time");
String scrambled = "ahlowemr";
for(String s : myList){
for(char c : scrambled.toCharArray()){
if(!s.contains(c)){ //doesn't allow character c
myList.remove(s);
}
}
}
If you want to remove items from a list while you iterate it, you should use an Iterator, also, the contains(...) method expects a String, not a char.
Here is what you can do:
for(Iterator<String> it = myList.iterator(); it.hasNext();){
String s = it.next();
for(char c : scrambled.toCharArray()){
if(!s.contains(String.valueOf(c))){
it.remove();
break;
}
}
}
ArrayList<String> myList = new ArrayList<String>();
myList.add("home");
myList.add("shop");
myList.add("salmon");
myList.add("time");
String scrambled = "ahlowemr";
for(int i = 0; i < myList.size(); i++) {
for(char c : scrambled.toCharArray()){
if(!myList.get(i).contains(c.toString())){ //doesn't allow character in that position
// There is a simple way using a regex or maybe a hashtable
myList.remove(s);
break; // break will jump into the next list value
}
}
}
java-8 solution for completeness:
ArrayList<String> myList = new ArrayList<>();
myList.add("home");
myList.add("shop");
myList.add("salmon");
myList.add("time");
String scrambled = "ahlowemr";
myList = myList.stream()
.filter(s -> scrambled.chars()
.allMatch(c -> s.contains(String.valueOf((char) c))))
.collect(Collectors.toCollection(ArrayList<String>::new));

Displaying group of elements in an Arraylist

i'm trying to display few elements of an arraylist if contition is true. The method gets String that should be found in arrayList. After that there are some other values that are contained after the line in List that has beed found.
I need to print thause line's out that would be 1_4_1334-Automatic.... I have tried to use Iterator but with no luck. It just seens that i just cannot get it.
So if am looking for 2210002_4_1294-Group i should get all strings that contain "Automatic" till 2210003_4_1295-Group is reached.
Any idea how it could be done ?
Thanks a lot :)
MyArrayList:
2210002_4_1294-Group
1_4_1334-Automatic
2_4_1336-Automatic
3_4_1338-Automatic
4_4_1340-Automatic
5_4_1342-Automatic
6_4_1344-Automatic
7_4_1346-Automatic
8_4_1348-Automatic
9_4_1350-Automatic
2210003_4_1295-Group
1_4_1378-Automatic
2_4_1380-Automatic
2210004_4_1296-Group
1_4_1384-Manual
2_4_1386-Manual
Method might look like this:
private void findValueInList(String group){
Iterator<String> iter = arrayList.iterator();
while(iter.hasNext()){
String name = iter.next();
if(name.equals(group)){
here i need to get ValueThatINeed
}
}
}
I guess your question is already answered Here
Simply iterate over your arraylist and check each value like the code below:
ArrayList<String> myList ...
String searchString = "someValue";
for (String curVal : myList){
if (curVal.contains(searchString)){
// The condition you are looking for is satisfied
}
}
I solved it like this:
private ArrayList<String> filterList(String nameToFind) {
ArrayList<String> elements = new ArrayList<String>();
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(nameToFind)) {
while (list.get(i+1).contains("Manual") || list.get(i+1).contains("Automatic")) {
elements.add(list.get(i+1));
i++;
}
}
}
return elements;
}

How to add strings into an arraylist between two strings

I am trying to figure out how to add a string, into a string ArrayList, between two strings that are already in. So if I have this
ArrayList<String> List = new ArrayList<String>();
List.add("Yes");
List.add("No");
List.add("Maybe");
How would I go along putting the word "Or" between them and make the ArrayList contain
"Yes" "Or" "No" "Or" "Maybe"?
I have three advices.
First, to name the variables, start with lower-case.
Second, use List as type of variable, instead of ArrayList, you will thank me later, trust me.
Third, to do what you ask for, there is overloaded method add for choosing position :
List<String> list = new ArrayList<String>();
list.add("Yes");
list.add("No");
list.add(1,"Maybe"); //insert into position 1 and shift everything to the right.
For this example, if you use System.out.println(list);, you will get this output :
[Yes, Maybe, No]
For adding Or instruction, it would be like this :
List<String> list = new ArrayList<String>();
list.add("Yes");
list.add("No");
list.add("Maybe");
list.add(1, "Or");
list.add(3, "Or");
System.out.println(list);
Output :
[Yes, Or, No, Or, Maybe]
Also, if you want to make your program more re-usable, you can write a method, that will do this for you for any case of list :
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("Yes");
list.add("No");
list.add("Maybe");
list.add("Probably");
list.add("Never");
List<String> orList = addOr(list);
System.out.println(orList);
}
public static List<String> addOr(List<String> list){
List<String> newList = new ArrayList<>();
int count = 0;
for(String text : list){
count++;
newList.add(text);
if (count != list.size()){
newList.add("Or");
}
}
return newList;
}
Having this output :
[Yes, Or, No, Or, Maybe, Or, Probably, Or, Never]
However, if you want to use that list for outputing some message for user, it is not good idea to add "Or", because it is really not part of information. Rather it is good, to create method, which will create output String you desire.
This code
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("Yes");
list.add("No");
list.add("Maybe");
list.add("Probably");
list.add("Never");
String niceOutput = addOr(list);
System.out.println("Choose from following options: " + niceOutput);
}
public static String addOr(List<String> list){
String orText = "";
int count = 0;
for(String text : list){
count++;
orText += '\'' + text + '\'';
if (count != list.size()){
orText += " or ";
}
}
return orText;
}
Having this output :
Choose from following options: 'Yes' or 'No' or 'Maybe' or 'Probably' or 'Never'
According to Add object to ArrayList at specified index
List.add(1, "or")
List.add(3, "or")
This should solve your problem.

Categories