I was trying to do something like:
ArrayList<String> getMerged ( String host, String port, String filesToCopy ){
ArrayList<String> merged = new ArrayList<String>();
merged.add(host);
merged.add(port);
merged.addAll(filesToCopy.split(",")); //which is invalid
return merged;
}
I want to know if we can add elements of filesToCopy.split(",") with out having the overhead of using a loop.
Also, if the above operation can be done in a string array, say String[] merged (can pass filesToCopy also as String[] if needed), it would be even better coz in the end, I'll be converting this arrayList into an array.
I'm novice in Java programming, so please don't mind if this is a silly question.
You could do this in a single array:
String[] files = filesToCopy.split(","); // filesToCopy is an ArrayList, so I'm not
// sure how this works; I'm assuming it's
// a typo. Just get the files array somehow
String[] merged = new String[2 + files.length];
merged[0] = host;
merged[1] = port;
for (int i = 2; i < merged.length; i++) {
merged[i] = files[i-2];
}
Or, without "the overhead of a loop":
merged[0] = host;
merged[1] = port;
System.arraycopy(files, 0, merged, 2, files.length);
Of course, this still uses a loop "behind the scenes," which is unavoidable.
ArrayList.addAll method requires a Collection as a parameter, so just pass the filesToCopy:
String [] getMerged ( String host, String port, ArrayList<String> filesToCopy ){
ArrayList<String> merged = new ArrayList<String>();
merged.add(host);
merged.add(port);
merged.addAll(filesToCopy);
return merged.toArray(new String[merged.size());
}
PS: I just a matter of opinion, but if I can choose between arrays and Collections, I always prefer to work with Collections (List, Set). Variable size and easy insertions are things to take into account.
I am not sure about what your need is.But i am sure anyone of the below methods will surely help you..
1.Covert String With Comma To A ArrayList
Program:
import java.util.Arrays;
....
String name="java,php,c";
List<String> list=Arrays.asList(name.split(","));
System.out.println(" "+list);
OutPut:
[java, php, c]
2.Covert ArrayList To StringArray
Here we can convert the same arraylist that we got in 1st method to string array.
Program:
String []names=list.toArray(new String[list.size()]);
for(String s:names){
System.out.println(""+s);
}
OutPut:
java
php
c
3.Covert ArrayList To Comma Seperated String
Here we can convert the same arraylist that we got in 1st method to string array.
For this you need To add commons-lang3-3.2.1.jar into your classpath or project libarary.
You can Download The commons-lang3-3.2.1.jar (HERE)
Program:
import org.apache.commons.lang3.StringUtils;
.....
String name=StringUtils.join(list, ",");
System.out.println("name="+name);
OutPut:
name=java,php,c
4.Updated Program
This might me the method that you needed
public String[] getMerged(String host, String port, String filesToCopy) {
String files[] = filesToCopy.split(",");
String[] merged = new String[(2 + files.length)];
merged[0] = host;
merged[1] = port;
System.arraycopy(files, 0, merged, 2, files.length);
return merged;
}
Check out these methods and notify me if your need is something other than these methods..
Related
Hello everyone i am trying to remove an name that the user has put in from an String Array, i am new to programming and i have tried this but it doesn't work. Can someone help me or tell me what i am doing wrong?
String [] myName = {"Testname","Charel","melissa","Kelly"};
removeName(myName);
public void removeName(String[] names )
{
Scanner sc = new Scanner(System.in);
String name = "";
name = sc.nextLine();
for (int i = 0; i < names.length; i++) {
name = names[i-1];
}
}
How can i do this?
You probably need to use Lists for this. Your list will be a list of String, and use remove() method to do this.
An array's length is fixed and can't be changed this way.
Useful Link : Removing items from a list
First off, an array does not change size after it is initialized, the only way to change the size of an array is to replace it with a new array! So in order to not end up with a double entry or an empty field, you would need to make a new array that is one size shorter, and write the names you want to keep into that.
An array might be ill-suited for your purposes, so consider using a list or an ArrayList. A list can be resized, so removing an element will automatically shorten the list. I recommend you look into that.
Lastly, you currently aren't even comparing your input to your fields. Replace name = names[i-1]; with something along the lines of
if(name.equals(names[i]))
//TODO: Remove from list
See here for more details about String.equals()!
Also, keep in mind that the user input might not match any name at all, so prepare for that case as well!
To remove an element from an array in Java, you need to create a new array and copy over all the elements you want to keep. That is because Java arrays are fixed-size.
For example, to remove an element at a particular index, you could do it like this:
public static String[] remove(String[] array, int index) {
String[] result = new String[array.length - 1];
System.arraycopy(array, 0, result, 0, index);
System.arraycopy(array, index + 1, result, index, result.length - index);
return result;
}
You would then remove melissa from your array as follows:
String[] names = { "Testname", "Charel", "Melissa", "Kelly" };
names = remove(names, 2);
System.out.println(Arrays.toString(names));
Output
[Testname, Charel, Kelly]
Of course, it would be much easier to do it using a List:
List<String> names = new ArrayList<>(Arrays.asList("Testname", "Charel", "Melissa", "Kelly"));
names.remove(2);
System.out.println(names);
Or:
List<String> names = new ArrayList<>(Arrays.asList("Testname", "Charel", "Melissa", "Kelly"));
names.remove("Melissa");
System.out.println(names);
Output of both is the same as above.
There are some simple methods using java api provide by jdk, for example:
String [] myName = {"Testname","Charel","melissa","Kelly"};
List<String> container = new ArrayList(Arrays.asList(myName));
container.remove("Charel");
String[] result = new String[myName.length - 1];
container.toArray(result);
Alternatively you can also use this to convert array to list,
Collections.addAll(container, myName);
String [] myName = {"Testname","Charel","melissa","Kelly"};
removeName(myName);
public void removeName(String[] names )
{
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
for (int i = 0; i < names.length; i++) {
if(names[i]==name)
{
for(int j=i;j<names.length-1;j++)
{
names[j]=names[j+1];
}
}
}
}
I am currently working on a project where I need to check an arraylist for a certain string and if that condition is met, replace it with the new string.
I will only show the relevant code but basically what happened before is a long string is read in, split into groups of three, then those strings populate an array. I need to find and replace those values in the array, and then print them out. Here is the method that populates the arraylist:
private static ArrayList<String> splitText(String text)
{
ArrayList<String> DNAsplit = new ArrayList<String>();
for (int i = 0; i < text.length(); i += 3)
{
DNAsplit.add(text.substring(i, Math.min(i + 3, text.length())));
}
return DNAsplit;
}
How would I search this arraylist for multiple strings (Here's an example aminoAcids = aminoAcids.replaceAll ("TAT", "Y");) and then print the new values out.
Any help is greatly appreciated.
In Java 8
list.replaceAll(s-> s.replace("TAT", "Y"));
There is no such "replace all" method on a list. You need to apply the replacement element-wise; the only difference vs doing this on a single string is that you need to get the value out of the list, and set the new value back into the list:
ListIterator<String> it = DNAsplit.listIterator();
while (it.hasNext()) {
// Get from the list.
String current = it.next();
// Apply the transformation.
String newValue = current.replace("TAT", "Y");
// Set back into the list.
it.set(newValue);
}
And if you want to print the new values out:
System.out.println(DNAsplit);
Why dont you create a hashmap that has a key-value and use it during the load time to populate this list instead of revising it later ?
Map<String,String> dnaMap = new HashMap<String,String>() ;
dnaMap.push("X","XXX");
.
.
.
dnaMap.push("Z","ZZZ");
And use it like below :
//Use the hash map to lookup the temp key
temp= text.substring(i, Math.min(i + 3, text.length()));
DNAsplit.add(dnaMap.get(temp));
Is it possible to split a string into an string array that hasn't been declared?
I want to add a string array to a list, so currently I have it set like this vars.add(new String[]{s}); where s is a string. Is there anyway to make it add s.split("|")?
Or is the only option:
String [] ns = s.split("|");
vars.add(ns);
I was playing in netbeans, where I would this make a string array, with this string "A|C|D|E":
new String(s).split("|");
Is this what you're looking for?
ArrayList<String[]> vars = new ArrayList<String[]>();
String s = "A|C|D|E";
vars.add(s.split("\\|"));
Note that if you want to add the Strings individually to the list, you must do it slightly differently.
ArrayList<String> vars = new ArrayList<String>();
String s = "A|C|D|E";
for (Sting str : s.split("\\|"))
vars.add(str);
I'm trying to bubble sort string data that was input into an array in descending and ascending order.
The following is the code so far:
import java.util.*;
public class nextLineArray
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String names[]=new String[12];
System.out.println("Enter the 12 names: ");
//Load Array
for(int i = 0; i < 12; i++)
{
names[i] = input.nextLine();
}
//Print initial list
System.out.println("List of names via input:"+ names);
//Print descending order list
String descSort;
descSort=bubbleSortDesc(names);
System.out.println("Names listed sorted in descending order (via BubbleSort): "+descSort);
}
public static String bubbleSortDesc(String[] names)
{
String temp;
int passNum, i, result;
for(passNum=1; passNum <= 11; passNum++)
{
for(i = 0; i<=(11-passNum); i++)
{
result=names[i].compareToIgnoreCase(names[i+1]);
if(result>0)
{
temp=names[i];
names[i]=names[i+1];
names[i+1]=temp;
}
}
}
return names;
}
}
When I try to return the sorted array to the main method it gives me the following error on the return line:
Incompatible Types
Our online instructor just started us out with using multiple methods and arrays at the same time and it is quite confusing...please excuse me if any of my mistakes appear to be obvious.
Edit: I have fixed the initial problem thanks to Alexandre Santos in the comments, I am now running into a problem when executing the program after inputting the data, instead of printing the strings in the array it prints out
[Ljava.lang.String;#6d782f7c
Take a look at the method
public static String bubbleSortDesc(String[] names)
The return of that method is supposed to be a String (only one), but you are returning the parameter "names", which is an array of strings. The "[]" after the String identifies it as an array.
I am not going to do your homework for you, so a hint: check if the return type of the method bubbleSortDesc should be one String or an array of Strings.
Good luck.
There are 2 points to fix. First you should return String array
public static String[] bubbleSortDesc(String[] names)
and therefore you should define it like this:
String descSort[];
public static String bubbleSortDesc(String[] names)
should be
public static String[] bubbleSortDesc(String[] names)
and also declare descSort as String array.
Also you are just printing the array objects. This will not print the list for you. You have iterate over the array.
Include this in you code:
for (String name:names)
{
System.out.println(name);
}
Do the same for descSort too....
You can fix your print command by changing it to the following:
System.out.println("Names listed sorted in descending order (via BubbleSort): "+ java.util.Arrays.deepToString(descSort));
If you want the nitty gritty, descSort is a String[]. In Java when you convert String[] into a String it gives you that crazy string representation. You have to instead converte each entry in the array to a String individually. Fortunately the deepToString method will do that for you.
I have a list of URL's added to a String[] with this.
try {
Elements thumbs = jsDoc.select("div.latest-media-images img.latestMediaThumb");
List<String> thumbLinks = new ArrayList<String>();
for(Element thumb : thumbs) {
thumbLinks.add(thumb.attr("src"));
}
for(String thumb : thumbLinks) {
System.out.println(thumbLinks.get(1));
}
}
How can i add each String that is loaded into a separate String?
EDIT:
SO as the images are loaded into the thumbLinks list. I want to get each link to a seperate
String url1;
String url2;
String url3;
If you expect a fixed number of items, and you have a fixed number of String variables, you have little choice but something like:
String url0 = thumbLinks.get(0);
String url1 = thumbLinks.get(1);
...
String url5 = thumbLinks.get(5);
Well, you could do something grim with reflection, I guess. But probably best to avoid this at all.
take a String array of the size of your ArrayList object - thumbLinks in your case. take an int variable and initialize it with zero. I have made some changes in your code just have a look:
try{
Elements thumbs = jsDoc.select("div.latest-media-images img.latestMediaThumb");
List<String> thumbLinks = new ArrayList<String>();
for(Element thumb : thumbs) {
thumbLinks.add(thumb.attr("src"));
}
String[] urls = new String[thumbLinks.size()];
int x =0;
for(String thumb : thumbLinks) {
urls[x++] = thumb;
}
}catch(Excpetion e){
}
use urls for your purpose
ArrayList has method public <T> T[] toArray(T[] a) that you can call as described below on thumbLinks:
String[] url = new String[thumbLinks.size()];
url = thumbLinks.toArray(url);
Then, you will have an array of strings that you can access like this:
System.out.println(url[0]);
System.out.println(url[1]);
System.out.println(url[2]);
// etc, etc. all the say up to thumbLinks.size() - 1
While this is not exactly what you've asked for, it's pretty much the same thing. If you really want variables named url1, url2, url3, etc., you're likely going to have to code it line by line for every element in the list.
Just as an aside, you don't need an array to access the elements of your thumbLinks list directly. You can already do this:
System.out.println(thumbLinks.get(0));
System.out.println(thumbLinks.get(1));
System.out.println(thumbLinks.get(2));
// etc. all the way up to thumbLinks.size() - 1