Converting array list to a string array - java

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;
}

Related

Remove element in strings arraylist java [closed]

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.

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);
}

How to parse a string when compared to another string?

In Java, I want to extract the differences from one comma-separated string when compared to another.
e.g
The string I want to extract the differences from: 1,hello,fire,dog,green
The string I am comparing with : 1,hello,water,dog,yellow
So the result of the function would give me a arraylist of [3,fire] and[5,green] as those items are different than the items in the second string, which are 'water' and 'yellow'. The numbers are the index positions of each item detected to be a difference. The other items match and are not considered.
First, you can create your own Pair class (based on Creating a list of pairs in java), doesn't have to be template.
Then Do something like this:
Split the two strings:
List<String> toCompareSplit= Arrays.asList(toCompare.split(","));
List<String> compareWithSplit= Arrays.asList(compareWith.split(","));
Iterate the lists:
List<Pair> diffList= new ArrayList<Pair>();
for (int i= 0; i < toCompareSplit.size; i++){
if (!toCompareSplit.get(i).equals(compareWithSplit.get(i))){
Pair pair= new Pair(i+1, toCompareSplit.get(i));
diffList.add(pair);
}
}
If the lists aren't in the same size you can run to the end of the shortest one etc.
Why not just loop through by splitting the strings.
public static List<String> compareStrings(String str1, String str2) {
String[] arrStr1 = str1.split(",");
String[] arrStr2 = str2.split(",");
List<String> strList = new ArrayList<String>();
for(int index = 0; index < arrStr1.length; ++index) {
if (!arrStr1[index].equals(arrStr2[index])) {
strList.add("[" + index + "," + arrStr1[index] + "]");
}
}
return strList;
}
Beaware of index out of bounds exception..!!
var left = "1,hello,fire,dog,green";
var right = "1,hello,water,dog,yellow";
var result = left.Split(',').Zip(right.Split(','), Tuple.Create).Where(x => x.Item1 != x.Item2).ToArray();
Using C#, this will return an array of tuples of the different elements. Sorry I don't have a compiler to hand so may be some small syntax errors in there.

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.

Java split string from array

I have a string array that contains some information.
Example:
String [] testStringArray;
testStringArray[0]= Jim,35
Alex,45
Mark,21
testStringArray[1]= Ana,18
Megan,44
This is exactly how the information is. Now my problem is I want to make each element a seperate element in an array and I want to split it based on the \n character.
So I want
newArray[0]=Jim,35
newArray[1]=Alex,45
newArray[2]=Mark,21
newArray[3]=Ana,18
etc etc. I am aware of the split method but won't this just split each array element into a completely new array instead of combining them?
If anyone could help, it would be appreciated. Thanks
Something like this:
// Splits the given array of Strings on the given regex and returns
// the result in a single array.
public static String[] splitContent(String regex, String... input) {
List<String> list = new ArrayList<>();
for (String str : input) {
for (String split : str.split(regex)) {
list.add(split);
}
}
return list.toArray(new String[list.size()]);
}
you can call it this way:
String[] testStringArray = ...;
String[] newArray = splitContent("\n", testStringArray);
Because of the use of varargs you can also call it like this:
String[] newArray = splitContent("\n", str1, str2, str3, str4);
where strX are String variables. You can use any amount you want. So either pass an array of Strings, or any amount of Strings you like.
If you don't need the old array anymore, you can also use it like this:
String[] yourArray = ...;
yourArray = splitContent("\n", yourArray);
String[] testStringArray = new String[2];
ArrayList<String> result = new ArrayList<String>();
testStringArray[0]= "Jim,35\nAlex,45\nMark,21";
testStringArray[1]= "Jiam,35\nAleax,45\nMarak,21";
for(String s : testStringArray) {
String[] temp = s.split("\n");
for(String t : temp) {
result.add(t);
}
}
String[] res = result.toArray(new String[result.size()]);
Try This is working Code >>
String[] testStringArray = new String[2]; // size of array
ArrayList<String> result = new ArrayList<String>();
testStringArray[0]= "Jim,35\nAlex,45\nMark,21"; // store value
testStringArray[1]= "Ana,18\nMegan,44";
for(String s : testStringArray) {
String[] temp = s.split("\n"); // split from \n
for(String t : temp) {
result.add(t); // add value in result
System.out.print(t);
}
}
result.toArray(new String[result.size()]);
you can first merge the strings into one string and then use the split method for the merged string.
testStringArray[0]= Jim,35
Alex,45
Mark,21
testStringArray[1]= Ana,18
Megan,44
StringBuffer sb = new StringBuffer();
for(String s : testStringArray){
s = s.trim();
sb.append(s);
if (!s.endWith("\n")){
sb.append("\n");
}
}
String[] array = sb.toString().split("\n");
Try this. It is simple and readable.
ArrayList<String> newArray = new ArrayList<String>();
for (String s : testStringArray) {
newArray.addAll(Arrays.asList(s.split("\\n"));
}
Firstly, you can't write what you just did. You made a String array, which can only contain Strings. Furthermore the String has to be in markers "" like "some text here".
Furthermore, there can only be ONE String at one place in the array like:
newArray[0] = "Jim";
newArray[1] = "Alex";
And NOT like:
newArray[0] = Jim;
And CERTAINLY NOT like:
// Here you're trying to put 2 things in 1 place in the array-index
newArray[0] = Jim, 35;
If you wan't to combine 2 things, like an name and age you have to use 2D array - or probably better in your case ArrayList.
Make a new class with following object:
public class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
And afterwards go to your class where you want to use the original array, and write:
ArrayList<Person> someNameOfTheArrayList = new ArrayList<Person>();
someNameOfTheArrayList.add(new Person("Jim", 32));
someNameOfTheArrayList.add(new Person("Alex", 22));

Categories