How to get String[] String's to a seperate String? - java

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

Related

How can i remove an element from array in Java

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

Return the updated ArrayList<Characters> after removing the specified element at the index

I am trying to find out if there is a possibility of returning the updated ArrayList after removing the specified element at the index in a single line so that I can pass it on to the recursive function.
Below is a snippet of my code which tries to generate all valid parenthesis combinations given n pairs of "()" brackets.
My concern is in the recursive function call "findAllCombinations" where after some validations I want to remove one character at each recursive call from the arrayList courceSet. However sourceSet.remove(index) returns a character. Instead I want to pass the updated list after removing the character in one line. Is it possible ?
Note : The line below is syntactically wrong and just used for better illustration.
findAllCombinations(sourceSet.remove(index), soFar + singleBracket, singleBracket); .
I did go through the official documentation but did not find any help.
Any help is appreciated, and thanks for your time.
public class GenerateParenthesis {
char singleBracket;
List<String> answerSet = new ArrayList<String>();
char[] repoSet = {'(',')'};
public List<String> generateParenthesis(int n) {
String soFar = "(";
List<Character> sourceSet = new ArrayList<Character>();
for(int i = 0;i<n;i++){
sourceSet.add('(');
sourceSet.add(')');
}
findAllCombinations(sourceSet,soFar,'(');
return answerSet;
}
public void findAllCombinations(List<Character> sourceSet,String soFar,Character toRemove){
if(sourceSet.isEmpty()){
answerSet.add(soFar); // append to a answer set list containing all combinations
return;
}
for(int i = 0;i<2;i++){
singleBracket = repoSet[i];
int index = sourceSet.indexOf(singleBracket);
if(index!=-1) {
findAllCombinations(sourceSet.remove(index), soFar + singleBracket, singleBracket);
}
}
}
public static void main(String args[]){
GenerateParenthesis gp = new GenerateParenthesis();
List<String> ans = new ArrayList<String>();
ans = gp.generateParenthesis(3);
}
}
ArrayList (likely to most List implementations) is a mutable data structure: calling remove you modify the list rather than returning a new list without the removed element.
If you want the latter behavior, the quick and easy way is to do a copy of the list.
// (inside the if...)
// pass the original list to the constructor to make a copy
List<Character> sourceSetCopy = new ArrayList<>(sourceSet);
// modify the copy
sourceSetCopy.remove(index);
// use the modified copy
findAllCombinations(sourceSetCopy, soFar + singleBracket, singleBracket);

Finding common between Array-list of Strings

I've array-list "mArrayListvarinats" of String which contains pipe separated strings like
225356175|225356176|225356177|225356178|225356179|225356180|225356181|225356182|225356183|225356184|225356185|225356186|225356187|225356188|225356189|225356190|225356191|225356192
The size of mArrayListvarinats may be 0 upto n Now I want to find out common string between those Strings from mArrayListvarinats.
for ex. if it's size is two the code may be like as follows.
String temp[] = mArrayListvarinats.get(0).split("\\|");
String temp1[] = mArrayListvarinats.get(1).split("\\|");
and then loop will work on both the arrays to get common one.But how to achieve it for any no of size inside the loop as those temp arrays will be generated in the loop on mArrayListvarinats?
Something like this should work :
HashSet<String> allStrings = new HashSet<String>();
HashSet<String> repeatedStrings = new HashSet<String>();
for(String pipedStrings: mArrayListvarinats){
String temp[] = pipedStrings.split("\\|");
for(String str : temp){
if(!allStrings.add(str)){
repeatedStrings.add(str);
}
}
}
This way, you will have your HashSet allStrings that contains all your unique strings. And the other HashSet repeatedStrings which contains all the strings that appears more than once.
Try this short version:
public static void main(String[] args) {
List<String> a = new ArrayList<>(asList("225356176|225356177|225356178".split("\\|")));
List<String> b = new ArrayList<>(asList("225356175|225356176|225356177".split("\\|")));
a.retainAll(b);
b.retainAll(a);
System.out.println(b);
}
OUTPUT:
[225356176, 225356177]
Iterate through each of them and put them in a HashSet. If you get false while adding it means it's already there. You can put it in a separate Hashset. this way you will get a hashset of all unique string and an another hashset of strings that occured multiple times
Set<String> set=new HashSet<String>();
for (int i = 0; i < temp.length; i++) {
set.add(str[i]);
}
for (int i = 0; i < temp1.length; i++) {
set.add(str1[i]);
}
The set will contain common strings.
If you are only interested in getting common strings found in mArrayListvarinats variable, then you should use Set data structure. Set in java will only contain unique entries. From the example strings it sounds that you are collecting string which has numeric values. So there won't be any problem due to that. But if you are collecting alpha numeric value then you need to take care of alphabet's case, as Set collects values which are case sensitive. So for Set A is not equal to a.
This will find common among all your lists.
List<String> common = Arrays.asList(mArrayListvarinats.get(0).split("\\|"));
for(String varinats: mArrayListvarinats){
List<String> items = Arrays.asList(varinats.split("\\|"));
common = ListUtils.intersection(items,common);
}
But for this you have to use Apache commons collection library , which I hope is not a issue for you :)
Below code will return you the frequency of each string present in the array.
public static void main(String[] args) {
String mArrayListvarinats = "225356175,225356176,225356177,225356178,225356179,225356180,225356181,225356182,225356183,225356184,225356185,225356186,225356187,225356188,225356189,225356190,225356191,225356192,225356192";
List<String> list = Arrays.asList(mArrayListvarinats.split(","));
Set<String> uniqueWords = new HashSet<String>(list);
for (String word : uniqueWords) {
System.out.println(word + ": " + Collections.frequency(list, word));
}
}
String with frequency more than 1 are duplicates/common. You can take actions based on frequency.

Merging string-Array / arrayList without using loop

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..

String Arraylist get the item starting with this string

I have a array list in which I bind the data
This is a example
MyStrings =new ArrayList<String>();
MyStrings.add("Dog");
MyStrings.add("Cat");
MyStrings.add("Can");
MyStrings.add("Ant");
MyStrings.add("Str");
Now I have a string String sweet="c";
Now what OI want is to filter that Arraylist based on my string(sweet)
so the items of the MyStrings will be only Cat and Can
EDIT
I am really sorry for the trouble I got you but my main problem is that sweet is a editable
Ive tried using this code
public void onTextChanged(CharSequence s, int start, int before,int count) {
//adapter2.getFilter().filter(s);
//int length = filterEditText.getText().length();
filterME = filterEditText.getText();
List<String> MySortStrings =new ArrayList<String>();
for(int i=0;i<MyStrings.size();i++)
{
String newString = MyStrings.get(i);
if (newString.startsWith(filterME)){
}
}
//adapter2 = new LazyAdapterGetFriends(MyFriends.this,x);
//list.setAdapter(adapter2);
}
using this declaration
LazyAdapterGetFriends adapter2;
ArrayList<String> MyStrings;
//List<String> MyStrings;
EditText filterEditText;
Sorry for my wrong question..
Foolish me
List<String> MyStrings =new ArrayList<String>();
List<String> MySortStrings =new ArrayList<String>();
MyStrings.add("Dog");
MyStrings.add("Cat");
MyStrings.add("Can");
MyStrings.add("Ant");
MyStrings.add("Str");
String sweet="c";
for(int i=0;i<MyStrings.size();i++)
{
if(MyStrings.get(i).startsWith(sweet.toUpperCase()))
{
MySortStrings.add(MyStrings.get(i));
}
}
System.out.println(MySortStrings.size());
The list MySortStrings contains the Cat & Can
These days you can also use streams to do it easily:
stringList.stream().filter(s -> s.contains("c")).collect(Collectors.toList())
When you would only need to know if there is a string in the list containing your letter (not part of the question but very useful) you can do this:
stringList.stream().anyMatch(s -> s.contains("c"))
Use str.startsWith(String, int index)
Index will tell you from which index in the str it should start comparing
The naive algorithm will be that you just filter everything out like this:
ArrayList<String> filtered = new ArrayList<String>();
for(String s : MyStrings){
if(s.substring(0,1).toLowerCase().equals("c")){
filtered.add(s);
}
}
but then you have access time in O(n).
if you need a more faster way you probably need to use a Key,Value Structure with Key set to the String you need to filter. Or even a http://en.wikipedia.org/wiki/Trie, where you can easily filter on every character in the string. But then you will need extra time in building up this thing.
Okay, this should be it when using your TextWatcher Stuff (untested...)
private List<String> MySortStrings = new ArrayList<String>(); // assume that your data is in here!
private List<String> MySortedStrings = new ArrayList<String>(); // this will be the list where your sorted strings are in. maybe you could also remove all strings which does not match, but that really depends on your situation!
public void onTextChanged(CharSequence s, int start, int before,int count) {
for(String str : MySortStrings){
if(str.startsWith(s.toString()){
MySortedStrings.add(str);
}
}
}
If you want to remove items that don't match from MyStrings rather than create a new ArrayList you will need to use an Iterator as this is the only safe way to modify a ArrayList while iterating over it.
myStrings = new ArrayList<String>();
myStrings.add("Dog");
myStrings.add("Cat");
myStrings.add("Can");
myStrings.add("Ant");
myStrings.add("Str");
String sweet="c";
sweet = sweet.toLowerCase();
Iterator<String> i = myStrings.iterator();
while (i.hasNext()) {
if (! i.next().toLowerCase().startsWith(sweet)) {
i.remove();
}
}
You can use the apache commons-collections library as well:
CollectionUtils.filter(myStrings,
new Predicate() {
public boolean evaluate(Object o) {
return ! ((String)o).startsWith("c");
}
}
};
Any object for which the "evaluate" method of the Predicate class returns false is removed from the collection. Keep in mind, that like the solution above using the Iterator, this is destructive to the list it is given. If that is an issue, you can always copy the list first:
List<String> filtered = new ArrayList<String>(myStrings);
CollectionUtils.filter(filtered, ...);

Categories

Resources