This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
In Java, how can I test if an Array contains a certain value?
I'm trying to do a sort of:
for(String s : myArray)
{
if(s is in newArray) //how do you test this? i want something like
//if(newArray.indexOf(s)!=-1)
{
//do nothing
}
else
{
//add to newArray
}
}
can someone please help?
if(newAray.contains(s))
{
//do nothing
}
else
{
//add to newArray
}
You cannot add items to arrays at will, because arrays are of fixed size. You need to convert the array to a list first, then add items to te list, and finally convert the list back to array:
List<String> tmp = new ArrayList<String>(Arrays.asList(newArray));
for(String s : myArray) {
if(!tmp.contains(s)) {
tmp.add(s);
}
}
newArray = tmp.toArray(new String[tmp.size()]);
Related
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 1 year ago.
I have the following code:
public static void closestInSubnet(int[][] adjlist, short[][] addrs, int src, short[][] queries) {
// TODO
List<String> address = ToList(addrs);
List<String> quer = ToList(queries);
for (String i : address) {
System.out.println(i);
}
}
public static List<String> ToList(short[][] preList) {
List<String> list = new ArrayList<String>();
for (short[] i : preList) {
list.add(i.toString());
}
return list;
}
I want it to be printing out the lists converted to Strings however I am getting the following in console:
[S#7637f22
[S#4926097b
[S#762efe5d
[S#5d22bbb7
[S#41a4555e
[S#3830f1c0
[S#39ed3c8d
[S#71dac704
[S#123772c4
I'm sure there is a quick fix for this any help would be great. thanks
You are created a list of arrays. You are now looping through the list and attempting to print the list in one go. What you are seeing is the object ID of the arrays.
You need to add an inner loop to print the individual elements of each array.
This question already has answers here:
Removing empty element from Array(Java)
(5 answers)
Closed 6 years ago.
I'm trying to remove a specific character from an array by copying the non specified elements into a new array. However, when I initialize new array, the return value is giving me a bunch of null values instead of the non specified element array.
public String[] wordsWithout(String[] words, String target) {
String store[] = null;
for(int i = 0; i < words.length; i = i +1){
store = new String[words.length];
if(!words[i].equals(target)){
store[i] = words[i];
}
}
return store;
}
You are initializing the result array inside the loop. In other words, for each iteration of the loop, you initialize a new array, and lose the changes you made to the previous one. You should move the initialization outside the loop.
But that would also pose a problem, as you wouldn't be able to preemptively know the size of the resulting array. Java 8 allows you a much easier way to write such a method:
public String[] wordsWithout(String[] words, String target) {
return Arrays.stream(words)
.filter(w -> !w.equals(target))
.toArray(String[]::new);
}
EDIT:
As noted in the comments, the design of the OP could be preserved, and the results could be accumulated in a List. IMHO, it's less elegant, but it would work in older versions of Java too:
public String[] wordsWithout(String[] words, String target) {
List<String> store = new ArrayList<>();
for (String word : words) {
if (!word.equals(target)){
store.add(word);
}
}
return store.toArray(new String(store.size());
}
You are initializing the array each time in for loop. Please check.
This is happening because you have of this line: store = new String[words.length]. This means that you are initializing your new Array to an Array of words.length elements all of them being initialized by default with null.
The other problem I see is that you are initializing your Array inside the loop, so at each iteration you will overwrite the changes you have already made in the previous loop (if made any)
To copy the non-specified elements in your new array I will do like #Mureinik mentioned above.
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 6 years ago.
I have a method in a program that takes an ArrayList objects:
private ArrayList<T> list;
and subsequently can use this method to take all of the items, copy them to a String Array, and then remove the items from the original list.
Here is the method:
public String[] takeAll()
{
if (this.list.size() <= 0)
{
throw new NoSuchElementException("Unable to take elements from empty array list");
}//checks if list is empty
String[] targetArray;
targetArray = list.toArray(new String[list.size()]); //adds the Objects to the String[] targetArray
list.clear();
return targetArray;
}
Main that tests this:
public static void main(String args[])
{
SimpleList a;
a = new SimpleList(Position.FIRST, Position.LAST);
String[] b;
a.list.add("thing1");
a.list.add("thing2");
a.list.add("thing3");
a.list.add("thing4");
b = a.takeAll();
System.out.println("The String Array b contains: " + b);
}
When I run it, it returns something odd:
The String Array b contains: [Ljava.lang.String;#15db9742
What would I have to change to actually print out b where it should display {"thing1", "thing2", "thing3", "thing4"} ?
Try the Arrays.toString() method:
System.out.println("The String Array b contains: " + Arrays.toString(b));
In Java, if you ask it to print an Object like that, it will print the toString() of that object. The easiest way to print the array elements is to run it through a for loop and print each element of array.
This question already has answers here:
Why does Stream<T> not implement Iterable<T>?
(9 answers)
Closed 7 years ago.
I have this code:
List<String> strings = Arrays.asList("a", "b", "cc");
for (String s : strings) {
if (s.length() == 2)
System.out.println(s);
}
I want to write it using a filter and a lambda:
for (String s : strings.stream().filter(s->s.length() == 2)) {
System.out.println(s);
}
I get Can only iterate over an array or an instance of java.lang.Iterable.
I try:
for (String s : strings.stream().filter(s->s.length() == 2).iterator()) {
System.out.println(s);
}
And I get the same error. Is this even possible? I would really prefer not to do stream.forEach() and pass a consumer.
Edit: it's important to me not to copy the elements.
You need an iterable to be able to use a for-each loop, for example a collection or an array:
for (String s : strings.stream().filter(s->s.length() == 2).toArray(String[]::new)) {
Alternatively, you could completely get rid of the for loop:
strings.stream().filter(s->s.length() == 2).forEach(System.out::println);
You mention you don't want to refactor your for loop but you could extract its body in another method:
strings.stream().filter(s->s.length() == 2).forEach(this::process);
private void process(String s) {
//body of the for loop
}
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Removing an element from an Array (Java)
Is there a way I can get rid of some elements in an array.
for instance, if i have this array
int testArray[] = {0,2,0,3,0,4,5,6}
Is there a "fast" way to get rid of the elements that equal 0
int resultArray[] = {2,3,4,5,6}
I tried this function but I got lost using Lists
public int[] getRidOfZero(int []s){
List<> result=new ArrayList<>();
for(int i=0; i<s.length; i++){
if(s[i]<0){
int temp = s[i];
result.add(temp);
}
}
return result.toArray(new int[]);
}
Java arrays can't be resized. You need to create a new array.
Count the non-zero elements in the array. Create a new array that size. Copy the elements from the old to the new array, skipping over zero elements.
You can do this with lists. Your best bet is to create a list of Integers; add non-zero elements to it; then use toArray to create an array from the list.
You're quite close, but:
Your generics were messed up (List<> is syntactically invalid)
Your comparison was only adding the element if it was less than zero (rather than adding it if it was not equal to zero)
You were calling the wrong toArray() method.Because ints are primitives, you have to turn the list back into an array yourself.
public int[] getRidOfZero(int[] s) {
List<Integer> result = new ArrayList<Integer> ();
for (int i : s) {
if (i != 0) {
result.add(i);
}
}
int[] toReturn = new int[result.size()];
for (int i=0; i<result.size(); i++) {
toReturn[i] = result.get(i);
}
return toReturn;
}
Since you're starting with an array, you'll need to create a new array and copy the items from the old array, excluding the zeros.
If you remove a bunch of zeros at once, this is going to be fast.
Otherwise, you'll need to begin with the doubly-linked LinkedList.
LinkedList has an iterator that allows you to move along the list and remove elements, which will be a constant-time operation.