I am declaring a String array as:
String[] items = new String[10];
items[0] = "item1";
items[1] = "item2";
How can I find length of items in an efficient way that it contains only 2 elements. items.length returns 10.
I am running a loop already which runs to its length. I want to so something with this code without adding new code/loop to count number of not-null elements. What can I replace with items.length
for (int i = 0; i < items.length; i++) {
...
}
No. You will need to loop and see how many non-null elements there are.
Consider using e.g. an ArrayList<String> instead of a raw array.
UPDATE
To answer the new part of your question, your loop can become:
for (int i = 0; (i < items.length) && (items[i] != null); i++) {
...
}
Why not use a collection:
Vector <String> items;
items.add("item1");
items.add("item2");
int length = items.size();
It is 10 already it is just that 8 of the object are set to null so you could do following
int count = 0 ;
if(items!=null){
for(String str : items){
if(str != null){
count ++;
}
}
}
With the modified question in mind, you can absolutely do nothing. There is no attribute giving you the count of not null elements, so either you'd take another collection or you'd check each value for null.
I think may this will help u
public class T1 {
public static void main(String[] args) {
String[] items = new String[10];
items[0] = "item1";
items[1] = "item2";
System.out.println(getActualSize(items));
}
public static int getActualSize(String[] items)
{
int size=0;
for(int i=0;i<items.length;i++)
{
if(items[i]!=null)
{
size=size+1;
}
}
return size;
}
}
You need to iterate and check for null.
int count = 0;
for(int i = 0; i < items.length; i++){
if(items[i] != null){
count++;
}
}
count will give the number of occupied elements
To find a number of all non-null elements in array/collection (that are not neccesary in the beginning of array) you can use elegant guava solution: Iterables.size(Iterables.filter(items, Predicates.notNull())).
Related
Basicly im trying to look through an Arraylist to check if the same object is listed 2 times - and if: append to "tempFinalFilterSearchList"
Im not allowed to use Hashmap (School assignment).
UPDATE - This code actual works now... Now I just need to remove dublicates from "tempFinalFilterSearchList"
public List<Venue> filterToFinalSearchList()
{
for (int i=0; i < tempFilterSearchList.size(); i++)
{
int occurences=0;
for (int j = 0; j < tempFilterSearchList.size(); j++)
{
if (tempFilterSearchList.get(i).getVenueId() == tempFilterSearchList.get(j).getVenueId())
{
occurences++;
}
}
if (occurences == 2)
{
tempFinalFilterSearchList.add(tempFilterSearchList.get(i));
}
}
return tempFinalFilterSearchList;
}
if the same venueId is listed exact 2 times in "tempfilterSearchList", then the Object have to be added to "tempFinalFilterSearchList"...
have tried several different things now, without luck - And also search here / google - there alot of solutions, but all with Hashmap which im not allowed to use.
Thank you in advance for any advise.
First of all keep in mind that using the remove function inside a loop for the same list is not safe(Unless using an iterator).
I assume you have a class let's call it A that has the attribute venueId.
It looks something like this + other attributes that you want:
public class A {
private int venueId;
public A(int venueId) {
this.venueId = venueId;
}
public int getVenueId() {
return venueId;
}
public void setVenueId(int venueId) {
this.venueId = venueId;
}
}
1.Create a function that parses the list and counts the number of times an object with the same venueId repeats itself
public boolean doesVenueIdRepeatInList(int venueId, List<A> list) {
int timesRepeated = 0;
//Parse the list and count the number of items that have the same venueId
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getVenueId() == venueId) {
timesRepeated++;
}
}
//If the venueId repeats more than 3 times
if (timesRepeated >= 3) {
return true;
}
return false;
}
3.Now to the code that actually does what you asked.
We will parse the list and identify the the objects that repeat more than 3 times.
If they repeat more than 3 times we won't add them to the new list
List<A> tempFilterSearchList = Arrays.asList(
new A(1),
new A(2),
new A(1),
new A(2),
new A(3),
new A(1),
new A(2)
);
//We will be using a new list to put the result in
//It's not safe to use the delete function inside a loop
List<A> filteredList = new ArrayList<>();
//Count the number an object repeats and if it repeats more than 3 times store it inside repeatedVenueIds
for (int i=0; i < tempFilterSearchList.size(); i++)
{
int venueId = tempFilterSearchList.get(i).getVenueId();
boolean itRepeat3Times = doesVenueIdRepeatInList(venueId, tempFilterSearchList);
//If it doesn't repeat more than 3 times add it to the new list
if(!itRepeat3Times) {
filteredList.add(tempFilterSearchList.get(i));
}
}
You have your result inside filteredList
It is a better advanced option to use 'iterator' since it allows you to remove elements while iterating an arraylist
ArrayList<Integer> tempFilterSearchList = new ArrayList<Integer>(Arrays.asList(1,2,5,3,7,3,7,3) );
Iterator itr = tempFilterSearchList.iterator();
while (itr.hasNext())
{
int count = 0;
int number = (Integer)itr.next();
for (int i=0; i < tempFilterSearchList.size(); i++)
{
int x = tempFilterSearchList.get(i);
if (x == number)
{
count++;
}
}
if( count != 3 )
{
itr.remove();
}
}
"using the remove function inside a loop for the same list is not safe. " this will not be an issue if you use iterator in java which is a advance option in java language
Your code must look like the folowing. First of all you should loop over all the elements in tempFilterSearchList. Then for each element, you should count the number of times it appears in the list. I choosed rather to place all the positions where the current elements' venueId occures in separate List to further delete them easly.
ArrayList<Integer> occurrences = new ArrayList<Integer>()
for (int i=0; i < tempFilterSearchList.size(); i++)
for (int j=0; j < tempFilterSearchList.size(); j++){
if(tempFilterSearchList.get(i).getVenueId() ==tempFilterSearchList.get(j).getVenueId()){
occurrences.add(j)
}
}
if(occurrences.size() != 3){
for(int j:occurrences){
tempFilterSearchList.remove(occurrences[j])
}
}
}
I've scoured a couple of the SOF threads but can't seem to find the answer I'm looking for. Most of them provide an answer with code that's beyond the scope of what I have learned thus far.
I've tried quite a few different things and can't get this to work the way I need it to.
The program is supposed to take the given array, read it, find the given toRemove item, and re-print the array without the toRemove item.
I believe my issue is within the removeFromArray method
public static void main(String[] args)
{
String[] test = {"this", "is", "the", "example", "of", "the", "call"};
String[] result = removeFromArray(test, "the");
System.out.println(Arrays.toString(result));
}
public static String[] removeFromArray(String[] arr, String toRemove)
{
int newLength = 0;
for(int i = 0; i < arr.length; i++)
{
if(arr[i].contains(toRemove))
{
newLength++;
}
}
String[] result = new String[arr.length-newLength];
for(int i = 0; i < (result.length); i++)
{
if(arr[i].contains(toRemove))
{
}
else
{
result[i] = arr[i];
}
}
return result;
}
This is an assignment in my java class and we have not learned Lists (one of the answers I stumbled upon in my googling) yet so that is not an option for me.
As it is now, it should be outputting:
[this, is, example, of, call]
Currently it is outputting: [this, is, null, example, of]
Any and all help will be much appreciated!
You need 2 indices in the second loop, since you are iterating over two arrays (the input array and the output array) having different lengths.
Besides, newLength is a confusing name, since it doesn't contain the new length. It contains the difference between the input array length and the output array length. You can change its value to match its name.
int newLength = arr.length;
for(int i = 0; i < arr.length; i++)
{
if(arr[i].contains(toRemove))
{
newLength--;
}
}
String[] result = new String[newLength];
int count = 0; // count tracks the current index of the output array
for(int i = 0; i < arr.length; i++) // i tracks the current index of the input array
{
if(!arr[i].contains(toRemove)) {
result[count] = arr[i];
count++;
}
}
return result;
There's the error that #Eran pointed out in your code, which can solve your problem. But I'm going to discuss another approach.
For now, you're first iterating over the entire array to find the number of occurrences to remove, and then, you're iterating over the array to remove them. Why don't you just iterate over the array, just to remove them. (I know, your first loop is helping you to determine the size of the output array, but you don't need that if you use some List like ArrayList etc.)
List<String> resultList = new ArrayList<String>();
for(int i = 0; i < arr.length; i++)
{
if(!arr[i].contains(toRemove))
{
resultList.add(arr[i]);
}
}
And you can return the resultList, but if you really need to return an array, you can convert the resultList to an array like this:
String [] resultArray = resultList.toArray(new String[resultList.size()]);
And then return this array. See this approach live here on ideone.
Try this Java8 version
List<String> test = Arrays.asList("this", "is", "the", "example", "of", "the", "call");
test.stream()
.filter(string -> !string.equals("the"))
.collect(Collectors.toList())
.forEach(System.out::println);
You can use Java Stream instead, it will give you the expected result and also your code will be clearer and really smaller.
See the method below I wrote that solves your problem.
public static String[] removeFromArray(String[] arr, String toRemove) {
return Arrays.stream(arr)
.filter(obj -> !obj.equals(toRemove))
.toArray(String[]::new);
}
If you're unfamiliar with java Stream, please see the doc here
The following code removes all occurrences of the provided string.
Note that I have added few lines for validate the input, because if we pass a null array to your program, it would fail. You should always validate the input in the code.
public static String[] removeFromArray(String[] arr, String toRemove) {
// It is important to validate the input
if (arr == null) {
throw new IllegalArgumentException("Invalid input ! Please try again.");
}
// Count the occurrences of toRemove string.
// Use Objects.equals in case array elements or toRemove is null.
int counter = 0;
for (int i = 0; i < arr.length; i++) {
if (Objects.equals(arr[i], toRemove)) {
counter++;
}
}
// We don't need any extra space in the new array
String[] result = new String[arr.length - counter];
int resultIndex = 0;
for (int i = 0; i < arr.length; i++) {
if (!Objects.equals(arr[i], toRemove)) {
result[resultIndex] = arr[i];
resultIndex++;
}
}
return result;
}
I am trying to remove duplicated words from an array, and I keep getting null values. I'm not allowed to use java sorting methods so I have to develop my own. Here's my code:
public class Duplicate{
public static void main(String[] args){
String[] test = {"a", "b", "abvc", "abccc", "a", "bbc", "ccc", "abc", "bbc"};
removeDuplicate(test);
}
public static String[] removeDuplicate(String[] words){
boolean [] isDuplicate = new boolean[words.length];
int i,j;
String[] tmp = new String[words.length];
for (i = 0; i < words.length ; i++){
if (isDuplicate[i])
continue;
for(j = 0; j < words.length ; j++){
if (words[i].equals(words[j])) {
isDuplicate[j] = true;
tmp[i] = words[i];
}
}
}
for(i=0;i<words.length;i++)
System.out.println(tmp[i]);
return tmp;
}
}
I tried doing
if(words == null)
words == "";
But it doesn't work. I also want to return the tmp array with a new size.
For example, test array length = 9, after removing the duplicates,I should get a new array with a length of 7.Thank you for your help.
EDIT:
result i get:
a
b
abvc
abccc
null
bbc
ccc
abc
null
You're getting nulls because the result array contains fewer words than the input array. However, you're constructing the arrays of the same length.
You don't have to sort to solve this problem. However, if you're not allowed to use the tools provided by java.utils, then this is either a poorly contrived test question or whomever told you not to use the Java utility classes is poorly informed.
You can solve without sorting by doing (assuming Java 1.5+):
public class Duplicate {
public static void main(String[] args) {
String[] test = {"a", "b", "abvc", "abccc", "a", "bbc", "ccc", "abc", "bbc"};
String[] deduped = removeDuplicate(test);
print(deduped);
}
public static String[] removeDuplicate(String[] words) {
Set<String> wordSet = new LinkedHashSet<String>();
for (String word : words) {
wordSet.add(word);
}
return wordSet.toArray(new String[wordSet.size()]);
}
public static void print(String[] words) {
for (String word : words) {
System.out.println(word);
}
}
}
The output will be:
a
b
abvc
abccc
bbc
ccc
abc
I would go for hashset to remove duplicates, it will remove duplicates since hash function for the same string will give same value, and duplicates will be eliminated. Then you can convert it to a string.
I would recommend doing this with a different approach. If you can use an ArrayList, why not just create one of those, and add the non-duplicate values to it, like this:
ArrayList<String> uniqueArrayList = new ArrayList<String>();
for(int i = 0; i < words.length; i++){
if(!uniqueArrayList.contains(words[i])){ // If the value isn't in the list already
uniqueArrayList.add(words[i]);
}
}
Now, you have an array list of all of your values without the duplicates. If you need to, you can work on converting that back to a regular array.
EDIT
I really think you should use the above option if you can, as there is no clean or decently efficient way to do this only using arrays. However, if you must, you can do something like this:
You can use the code you have to mark values as null if they are duplicates, and also create a counter to see how many unique values you have, like this:
int uniqueCounter = 0;
for(int i = 0; i < isDuplicate.length; i++){
if(!isDuplicate[i]){
uniqueCounter++;
}
}
Then, you can create a new array of the size of unique items, and loop through the words and add non-duplicate values.
String[] uniqueArray = new String[uniqueCounter];
int uniqueIndex = 0;
int wordsIndex = 0;
while(index < uniqueArray.length){
// Check if words index is not a duplicate
if(!isDuplicate[wordsIndex]){
// Add to array
uniqueArray[uniqueIndex] = words[wordsIndex];
uniqueIndex++; // Need to move to next spot in unique.
}
// Need to move to next spot in words
wordsIndex++;
}
Again, I HIGHLY recommend against something like this. It is very poor, and pains me to write, but for the sake of example on how it could be done using an array, you can try it.
I don't have the time to write functioning code, but I would reccomend to first sort the array using Arrays.sort(stringArray) and then loop throug the array coparing one string to the previous. Strings that match the previous one are duplicates.
Note: This method is probably not the fastest one and though only should be used on small arrays or in tasks where performance does not matter.
What about this approach?
public static String[] removeDuplicate(String[] words){
// remember which word is a duplicate
boolean[] isDuplicate = new boolean[words.length];
// and count them
int countDuplicate = 0;
for (int i = 0; i < words.length ; i++){
// only check "forward" because "backwards checked" duplicates have been marked yet
for(int j = i + 1; j < words.length ; j++){
if (words[i].equals(words[j])) {
isDuplicate[j] = true;
countDuplicate++;
}
}
}
// collect non-duplicate strings
String[] tmp = new String[words.length - countDuplicate];
int j = 0;
for (int i = 0; i < isDuplicate.length; i++) {
if (isDuplicate[i] == false) {
tmp[j] = words[i];
j++;
}
}
// and return them
return tmp;
}
I tried to print the string without duplicate but i not getting the proper output and here I exposed my code snippets.
class Duplicatestring
{
public static void main(String [] args)
{
String word = "";
String[] ip ={"mani" ," manivannan","raghv ","mani"};
for(int i =0; i<ip.length; i++)
{
for(int j = i+1; j<=ip.length; j++)
{
if(ip[i].equals(ip[j])){
word = word+ip[i];
}
}
System.out.println(word);
}
}
}
And one more thing is I don't want use the collections that is my task and pleas give any proper solution for this.
Example:
Input -> {mani, manivanna,raghv, mani};
output -> {mani, manivanna,raghv}
If you don't want to use collections then I assume it's a homework, so I don't want to provide you a full solution, but I'll guide you.
You can have a helper array of the size of the original array. Now you write two nested loops and for each word, if you find a duplicate, you mark the helper array with 1.
After this procedure you'll have something like this in the helper array:
[0,0,0,1]
Now you iterate on the arrays in parallel and print the element only if the corresponding index in the helper array is 0.
Solution is O(n2).
Your loop is incorrect.
To solve the problem, you can use a Set to eliminate duplicated words.
If the problem must be solved by O(n^2) loops, the following code will work:
public class Duplicatestring {
public static void main(String[] args) {
String[] ip = { "mani", " manivannan", "raghv ", "mani" };
for (int i = 0; i < ip.length; i++) {
boolean duplicated = false;
//search back to check if a same word already exists
for (int j = i - 1; j >= 0; j--) {
if(ip[i].equals(ip[j])) {
duplicated = true;
break;
}
}
if(!duplicated) {
System.out.println(ip[i]);
}
}
}
}
if you want to remove the duplicate from the array call the below method and pass the array has the duplicate values.. it will return you the array with non-duplicate values..
call method here
ip = removeDuplicates(ip);
public static int[] removeDuplicates(int[] arr){
//dest array index
int destination = 0;
//source array index
int source = 0;
int currentValue = arr[0];
int[] whitelist = new int[arr.length];
whitelist[destination] = currentValue;
while(source < arr.length){
if(currentValue == arr[source]){
source++;
} else {
currentValue = arr[source];
destination++;
source++;
whitelist[destination] = currentValue;
}
}
int[] returnList = new int[++destination];
for(int i = 0; i < destination; i++){
returnList[i] = whitelist[i];
}
return returnList;
}
it will return you the non duplicates values array..!!
u may try this:
public class HelloWorld{
public static void main(String []args){
String[] names = {"john", "adam", "will", "lee", "john", "seon", "lee"};
String s;
for (int i = 0; names.length > i; i ++) {
s = names[i];
if (!isDuplicate(s, i, names)) {
System.out.println(s);
}
}
}
private static boolean isDuplicate(String item, int j, String[] items) {
boolean duplicate = Boolean.FALSE;
for (int i = 0; j > i; i++) {
if (items[i].equals(item)) {
duplicate = Boolean.TRUE;
break;
}
}
return duplicate;
}
}
output
john
adam
will
lee
seon
if string order does not matter for you, you can also use the TreeSet.. check the below code.. simple and sweet.
import java.util.Arrays;
import java.util.List;
import java.util.TreeSet;
public class MyArrayDuplicates {
public static void main(String a[]){
String[] strArr = {"one","two","three","four","four","five"};
//convert string array to list
List<String> tmpList = Arrays.asList(strArr);
//create a treeset with the list, which eliminates duplicates
TreeSet<String> unique = new TreeSet<String>(tmpList);
System.out.println(unique);
System.out.println();
Iterator<Integer> iterator = unique.iterator();
// Displaying the Tree set data
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
}
}
it will print as -
[five, four, one, three, two]
five
four
one
three
two
I have an array of strings, and I want to delete a particular string from that array. How can I do that? My code is:
private void nregexp(){
String str_nregexp = i_exp_nregexp.getText();
boolean b;
for(int i=0; i<selectedLocations.length; i++){
b= selectedLocations[i].indexOf(str_nregexp) > 0;
if(b){
String i_matches = selectedLocations[i];
........
........
}
}
}
I have to remove i_matches from selectedLocations.
I depends what you mean by "delete a particular String from an array". If you wish to remove its value, you can simply set its value to null, however if you mean actually remove that element from the array (you have an array of 5 elements and you want the result after deleting the element to be 4), this is not possible without copying the array with the item removed.
If you want this behavior, you might want to take a look at a dynamic list such as ArrayList or LinkedList
Edit: If you wanted a simple method to copy the array into an array with the String removed, you could do something like:
List<Foo> fooList = Arrays.asList(orgArray);
fooList.remove(itemToRemove);
Foo[] modifiedArray = fooList.toArray();
You will need to copy the array to a smaller array, omitting the string you don't want. If this is a common situation, you should consider using something other than an array, such as LinkedList or ArrayList.
If you really want to do it yourself, here is an example:
import java.util.Arrays;
public class DelStr {
public static String[] removeFirst(String[] array, String what) {
int idx = -1;
for (int i = 0; i < array.length; i++) {
String e = array[i];
if (e == what || (e != null && e.equals(what))) {
idx = i;
break;
}
}
if (idx < 0) {
return array;
}
String[] newarray = new String[array.length - 1];
System.arraycopy(array, 0, newarray, 0, idx);
System.arraycopy(array, idx + 1, newarray, idx, array.length - idx - 1);
return newarray;
}
public static void main(String[] args) {
String[] strings = { "A", "B", "C", "D" };
System.out.printf("Before: %s%n", Arrays.toString(strings));
System.out.printf("After: %s%n",
Arrays.toString(removeFirst(strings, "D")));
}
}
You cannot change the length of the array, after initializing an array its length is set. So you cannot delete the element directly, you can only replace it, also with null.
String[] arr = new String[10];
// fill array
...
// replace the fifth element with null
arr[4] = null;
If you want to change the length of the Array you should try a list instead:
List<String> list = new ArrayList<String>();
// fill list
...
// remove the fifth element
list.remove(4);
Could you show us your code? Why don't you use ArrayList, as it has a remove(index) and remove(object) support?
Edit: Perhaps
private void nregexp() {
String str_nregexp = i_exp_nregexp.getText();
boolean b;
List<String> list = new ArrayList<String>(Arrays.asList(selectedLocations));
for(Iterator<String> it = list.iterator(); i.hasNext();){
String e = it.next();
b = e.indexOf(str_nregexp) > 0;
// b = e.matches(str_regexp); // instead?
if(b){
String i_matches = s;
it.remove(); // we don't need it anymore
........
........
}
}
selectedLocations = list.toArray(new String[list.size()]);
}
I've reached this solution that allows you to remove all the elements that equal the removal element:
private static <T> T[] removeAll(T[] array, T element) {
if (null == array)
throw new IllegalArgumentException("null array");
if (null == element)
throw new IllegalArgumentException("null element");
T[] result = (T[]) Array.newInstance(array.getClass().getComponentType(), array.length);
int j = 0;
for (int i = 0; i < array.length; i++) {
if (!element.equals(array[i]))
result[j++] = array[i];
}
return Arrays.copyOf(result, j);
}
I also did some benchmarking and this solution is definitely better then using Lists. Although, if performance is not a problem here, I would use Lists.
If you really need to remove only one element (the first) #kd304 has the solution.