Am doing a simple android application.In that I am deleting an element from array using the following code.
arr_fav = {"1","2","3"};
for(int i= 0;i<arr_fav.length;i++)
{
if(current_id == Integer.parseInt(arr_fav[i]))
{
arr_fav[1] = null;
} }
By doing this am getting the array like arr_fav = {"1",null,"3"}.But I want like arr_fav = {"1","3"}.How to delete an element.Am new to this android development.Please help me to solve this.
its better to use arraylist
arr_fav = {"1","2","3"};
List<String> numlist = new ArrayList<String>();
for(int i= 0;i<arr_fav.length;i++)
{
if(current_id == Integer.parseInt(arr_fav[i]))
{
// No operation here
}
else
{
numlist.add(arr_fav[i]);
}
}
arr_fav = numlist .toArray(new String[numlist .size()]);
You don't.
Arrays can not be resized.
You would need to create a new (smaller) array, and copy the elements you wished to preserve into it.
A better Idea would be to use a List implementation that was dynamic. An ArrayList<Integer> for example.
Arrays in Java are not dynamic, you can use an ArrayList instead.
You can copy the array elements that you want into a new array
j = 0;
for(int i= 0;i<arr_fav.length;i++)
{
if(current_id != Integer.parseInt(arr_fav[i]))
{
arr_new[j++] = arr_fav[i];
} }
Use an ArrayList instead of an array. It supports features like deleting any element, dynamic size, and many more.
ArrayList<String> arr_fav_list = new ArrayList<String>();
arr_fav_list.addAll(arr_fav);
arr_fav_list.remove(1);
This will do the job ...
List x = new ArrayList(Arrays.asList(arr_fav));
x.remove(String.valueOf(current_id));
arr_fav = x.toArray();
try this:
ArrayList<String> rm = new ArrayList<String>();
rm .addAll(arr_fav);
rm .remove(1);
Try something like this
int[] intAry = new int[5];
// populate array with 0 to 4
for (int i=0; i < intAry.length; i++) {
intAry[i] = i;
}
List<Integer> aList = Arrays.asList(intAry); // change the array to a list of integers
aList.remove(3); // remove the item 3 (4th index)
aList.toArray(intAry); // convert list back to array
System.out.println("size of array=" + intAry.size()); // output array size should be 4
for (int i=0; i < intAry.length; i++) {
System.out.print(intAry[i] + " "); // should output "0 1 2 4 "
}
set
array_fav[1]=array_fav[2];
array_fav[2]=null;
You can do it using the following method..
public static String[] removeElements(String[] input, String deleteMe) {
List result = new LinkedList();
for(String item : input)
if(!deleteMe.equals(item))
result.add(item);
return result.toArray(input);
}
OR you could use ArrayUtils.
array = ArrayUtils.removeElement(array, element)
For simple arrays like this you can't do this in this way
here is the full sample code for this
int current_id = 2;
String[] arr_fav = { "1", "2", "3" };
for (int i = 0; i < arr_fav.length; i++) {
if (current_id == Integer.parseInt(arr_fav[i])) {
String[] arr_fav_tem = new String[arr_fav.length - 1];
arr_fav[1] = null;
int counter = 0;
for (int j = 0; j < arr_fav.length; j++) {
if (arr_fav[j] != null) {
arr_fav_tem[counter] = arr_fav[j];
counter++;
}
}
arr_fav = arr_fav_tem;
}
}
for (int i = 0; i < arr_fav.length; i++) {
System.out.println(arr_fav[i]);
}
String[] arr_fav =
{ "1", "2", "3" };
List<String> myList = Arrays.asList(arr_fav);
String currentId = String.valueOf(current_id);
for (int i = 0; i < arr_fav.length; i++)
{
if (arr_fav[i].equals(currentId))
{
myList.remove(i);
}
}
private String[] removeItem(String[] names,
int position) {
ArrayList<String> al_temp=new ArrayList<String>();// temporary ArrayList
for(int i=0;i<names.length;i++)
{
al_temp.add(names[i]);
}
al_temp.remove(position);
names= new String[al_temp.size()];//array cleared with new size
for(int i=0;i<al_temp.size();i++)
{
names[i]=al_temp.get(i);
}
return names;
}
Copy this method:
private static String[] deleteElement(String stringToDelete, String[] array) {
String[] result = new String[array.length];
int index = 0;
ArrayList<String> rm = new ArrayList<String>();
for(int i = 0; i < array.length; i++) {
rm.add(array[i]);
}
for(int i = 0; i < array.length; i++) {
if(array[i].equals(poistettava)) {
index = i;
}
}
rm.remove(index);
result = rm.toArray(new String[rm.size()]);
return result;
}
To delete element:
String[] array = {"1", "2", "3"};
array = deleteElement("3", array);
Related
I am creating an ArrayList of String Arrays in Java.. The code for the same is follows..
ArrayList<String[]> al = new ArrayList<String[]>();
for(int i = 0; i < t; i++) { // t is input by user representing size of arraylist
int k = sc.nextInt();
String[] s = new String[k]; // k string values input by user
}
Iterating to print the values of ArrayList
Iterator it = al.iterator();
while(it.hasNext()){
for(int i = 0; i < (it.next(new String[])).length; i++) { // error for dimension missing
System.out.println((it.next(new String[])).length); // error for dimension missing
}
}
I get an error of "array dimension missing" in the indicated lines. Please suggest how to convert ArrayList Object as String Array.
Try this
Iterator<String[]> it = al.iterator();
while(it.hasNext()){
String temp [] = it.next();
for(int i = 0; i < temp.length; i++) {
System.out.println(temp.length);
}
}
your new String[]
requires size, because you're making new array i.e
String[] myStringArray = new String[5];
also, your iteration to print values make no sense, try :
for(String[] stringArray: al) {
System.out.println("Size: " + stringArray.length);
for(String s: stringArray) {
System.out.println(s);
}
}
I want to remove duplicate String values inside my String[], but I am not sure quite how to do that.
Heres an example:
public static void main(String[] args){
String[] listofWords = new String [5];
listofWords[0] = "BMW";
listofWords[1] = "Audi";
listofWords[2] = "Mercedes";
listofWords[3] = "Audi";
listofWords[4] = "BMW";
for(int i = 0; i<listofWords.length-1; i++){
system.out.println(listofWords[i]);
}
}
How would I got about deleting the duplicates in this array and only have one of each make?
You can convert your String[] to Set:
String [] listofWords = new String [5];
listofWords [0] = "BMW";
listofWords [1] = "Audi";
listofWords [2] = "Mercedes";
listofWords [3] = "Audi";
listofWords [4] = "BMW";
Set<String> set = new HashSet<String>(Arrays.asList(listofWords));
System.out.println(set); //prints [Audi, Mercedes, BMW]
You can convert the Set back to String[] like this:
listofWords = set.toArray(new String[set.size()]);
I would recommend this solution using Java 8 streams
String[] result = Arrays.stream(listofWords).distinct().toArray(s -> new String[s]);
This also addresses the memory concerns you have expressed in the comments. It will just create an array with enough size to store distinct values and store the result there.
As a side note you could have initialized listofWords more easily like this
String[] listofWords = {"BMW", "Audi", "Mercedes", "Audi", "BMW"};
If memory is not a concern, convert to a set and back to array, like:
Set<String> mySet = new HashSet<String>(Arrays.asList(listofWords));
listofWords = mySet.toArray(new String[mySet.size()]);
If you have memory limits then you should sort the array:
Arrays.sort(listofWords);
Then remove the duplicates, like this:
public static int removeDuplicates(String[] A) {
int length=A.length;
if(length==0 || length==1) return length;
int i=1;
for(int j=1; j<length; j++){
if(!A[j].equals(A[j-1])){
A[i]=A[j];
i++;
}
}
if(i<length) A[i]=null;
return i;
}
This method will remove the duplicates and return the new array size.
Eg.
public static void main(String[] args) {
String[] listofWords = new String [5];
listofWords[0] = "BMW";
listofWords[1] = "Audi";
listofWords[2] = "Mercedes";
listofWords[3] = "Audi";
listofWords[4] = "BMW";
Arrays.sort(listofWords);
int n=removeDuplicates(listofWords);
for(int i = 0; i<n; i++){
System.out.println(listofWords[i]);
}
}
//JAVA-8 - Remove Duplicates
List li1 = new ArrayList<>(Arrays.asList(10, 22, 10, 20, 11, 22));
System.out.println("Duplicate elements: " + li1);
// Create new list from elements of original list
List li2 = (List) li1.stream().distinct().collect(Collectors.toList());
// ArrayList with duplicates removed
System.out.println("Non-duplicate elements: " + li2);
It is straightforward to do in-place if you don't need to preserve the order of appearance in the array: sort the array first and use two pointers to iterate through the array:
Arrays.sort(listofWords);
int i = 0, j = 0;
while (j < listofWords.length) {
// Copy the element from the j-th position to the i-th position.
listofWords[i] = listofWords[j];
// Increment j while the word at position j equals the word at position i.
while (j < listofWords.length && listofWords[j].equals(listofWords[i])) {
++j;
}
// Increment i, to be the next unique element index.
++i;
}
// i currently points to the element after the last non-duplicate element, so
// ideally we would throw away elements [i..listofWords.length)
// However, you can't resize an array in Java.
// This loop just nulls out the remaining elements, since their contents are all
// already in the array.
while (i < listofWords.length) {
listofWords[i++] = null;
}
You can try the below solution :
public static void main(String[] args) {
String strArray[] = new String[]{"bmw","audi","bmw","honda","Yamaha","Yamaha","maruti","hyundai","hyundai"};
HashSet setOfStrings= new HashSet<String>();
for(int i=0;i<strArray.length;i++){
boolean result=setOfStrings.add(strArray[i]);
if(!result){
System.out.println("duplicate elements include...."+strArray[i]);
}
}
Object[] newString= new Object[strArray.length];
newString=setOfStrings.toArray();
System.out.println("Array without Duplicates......."+Arrays.toString(newString));
}
import java.util.Arrays;
/**
* #author Kishore Diyyana
* Simple Bruteforce approach
*/
public class RemoveDupilcates {
public static void main(String[] args) {
RemoveDupilcates removeDups = new RemoveDupilcates();
removeDups.removeDups();
}
public void removeDups() {
int[] numbers = new int[] {10, 22, 10, 20, 11, 22};
int[] temp = new int [numbers.length];
int count = -1;
for (int i=0; i<numbers.length;i++) {
boolean hasFound = false;
for (int j = i+1; j< numbers.length; j++) {
if (numbers[i] == numbers[j]) {
hasFound = true;
break;
}
}
if (!hasFound) {
count++;
System.out.println(numbers[i]);
temp[count] = numbers[i];
}
}
int[] outpout = null;
if (count < numbers.length) {
outpout = new int [count];
System.arraycopy(temp, 0, outpout, 0, count);
}
System.out.println(Arrays.toString(outpout));
}
}
Lets say we have this array: String[] arr1 = {"a", "b", "c", "a"};
What I'm trying to do is remove duplicate String (In this case "a") and add its value to another String[] called duplicates. When the duplicate is added to the "duplicates" array, the amount of times it occured wrongfully in the array arr1 is concatenated next to it. (recurredValue + amount) so in this example it would be a 1. I have searched for this before and all of them included usage of Lists, ArrayLists, or Sets. Please do not use any of them.
Use below code:-
public static String[] removeDuplicates(String[] numbersWithDuplicates) {
// Sorting array to bring duplicates together
Arrays.sort(numbersWithDuplicates);
String[] result = new String[numbersWithDuplicates.length];
String[] duplicate = new String[numbersWithDuplicates.length];
String previous = numbersWithDuplicates[0];
result[0] = previous;
int counter=1;
int duplicateCounter=0;
for (int i = 1; i < numbersWithDuplicates.length; i++) {
String ch = numbersWithDuplicates[i];
if (previous != ch) {
result[counter++] = ch;
}
else
{
duplicate[duplicateCounter++]=ch;
}
previous = ch;
}
for (int i = 0; i < result.length; i++) {
System.out.println(result[i]);
}
System.out.println("Duplicate Values are ---");
for (int i = 0; i < duplicate.length; i++) {
System.out.println(duplicate[i]);
}
return result;
}
maybe something like this you can use
public static void main(String[] args) {
String[] arr1 = {"a", "b", "c", "a", "a"};
String[] duplicates = new String[arr1.length];
boolean d = false;
int count = 0;
String dup = "";
for(int i = 0;i < arr1.length;i++){
count = 0;
dup = "";
d = false;
for(int j = 0;j < arr1.length;j++){
if(i != j){
if(arr1[i].equals(arr1[j]) && !arr1[i].equals("")){
arr1[j] = "";
d = true;
count++;
dup = arr1[i];
}
}
}
if(d){
duplicates[i] = dup + count;
d = false;}
}
for(int k = 0;k < duplicates.length;k++)
System.out.println(duplicates[k]);
}
Well, one solution is to create 2 arrays and have one hold the unique strings and the other its integer counter. As you index through your sample string array, add the unique strings and increment the incidents. This is not a very elegant or efficient solution but it should work.
I am having a resultList which is a string list were each element in this list is also a List<String>. Now I want to put my data into a csv sheet. For that I am using opencsv.
List<String[]> data = new ArrayList<String[]>();
for(int m = 0; m < resultList.get(0).size(); m++) {
for (int i = 0; i < resultList.size(); i++) {
data.add(new String[] {resultList.get(i).get(m).toString()});
}
}
writer.writeAll(data);
//close Writer
writer.close();
My data should look like that:
However, my implementation gives me that:
In my implementation I am taking, knowing that every sublist has the same length, from each sublist the first element and add it to the array. Why am I getting this long row?
I appreciate your replies!
Because your loop is incorrect. You constructed a new String array in every inner loop, so every array has only on element.
Try the following code:
List<String[]> data = new ArrayList<String[]>();
for(List<String> strlist : resultList) {
String[] array = new String[strlist.size()];
int offset = 0;
for(String s : strlist) {
array[offset ++] = s;
}
data.add(array);
}
============== Edited bellow ==================
I've re-ordered the loop to match your output requirement. Also, a sample input is provided to test the algorithm.
List<List<String>> resultList = new ArrayList<List<String>>();
for (int i = 1; i <= 9; i++) {
List<String> innerList = new ArrayList<String>();
resultList.add(innerList);
for (int j = 1; j <= 9; j++) {
innerList.add(j + "");
}
}
List<String[]> data = new ArrayList<String[]>();
for(int m = 0; m < resultList.get(0).size(); m++) {
String[] array = new String[resultList.size()];
for (int i = 0; i < resultList.size(); i++) {
array[i] = resultList.get(i).get(m).toString();
}
data.add(array);
}
for(String[] array : data) {
System.out.println(Arrays.toString(array));
}
I need to compare the value from List with the value from array.
I wrote the following:
public class JavaApplication3 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic hereut
List<String> l = new ArrayList<String>();
l.add("test");
l.add("b");
String v = "";
String s = "";
String[] arr = {"test", "c", "b"};
for (int i = 0; i < l.size(); i++){
v = "";
s = "";
//System.out.println(l.get(i));
for (int j = 0; j < arr.length; j++){
if (l.get(i).equals(arr[j])){
s = i + "";
}else{
s = arr[i];
}
v = v + s + ",";
}
System.out.println(v);
}
}
}
I obtain the following
0,test,test,
c,c,1
but I need the result like this:
0, c, 1,
Looking at your expected result I guess the requirement like that:
for each element in the array, check if it is on the list. If it is on the list, print the index from the list for this element, otherwise print the element itself. So the algorithm should do:
array[0] = "test" -> found at index 0 -> print "0"
array[1] = "c" -> not found -> print "c"
array[2] = "b" -> found at index 1 -> print "1"
The outer loop should iterate over the array. Then, for each array item, iterate over the list until you find the same element. For a first draft, don't collect the output in a string but print it immediatly. You can create the string when the algorithm works as expected.
You have six iterations, each of which inserts something into the output.
You want three iterations, each of which checks for membership in the first list. You can do that with the List.contains() method. (If the list were long, you might want to consider using a Set instead of a List, to allow checking set membership more quickly.)
How about this:
public static void main(String[] args) {
// TODO code application logic hereut
List<String> l = new ArrayList<String>();
l.add("test");
l.add("b");
String v = "";
String s = "";
String[] arr = {"test", "c", "b"};
int pointer = 0;
for (int i = 0; i < l.size(); i++){
//System.out.println(l.get(i));
for (; pointer < arr.length;){
if (l.get(i).equals(arr[pointer])){
s = i + "";
v = v + s + ",";
pointer++;
break;
}else{
s = arr[i];
}
pointer++;
v = v + s + ",";
}
}
System.out.println(v);
}
Try to break things down to their high level steps.
For each string in the array
find its place in the list
if the item is in the list
print its position
else
print the missing string
print a common and space
Once you have this you can spot that find its place in the list could be a method that returns the place in the list or -1 if it isn't in the list. Here's what I made (might have renamed a few things and used a StringBuilder but you can ignore that for the moment).
import java.util.ArrayList;
import java.util.List;
public class Example {
public static void main(final String[] args) {
final List<String> listToSeach = new ArrayList<String>();
listToSeach.add("test");
listToSeach.add("b");
final String[] arrayElementsToFind = { "test", "c", "b" };
final StringBuilder output = new StringBuilder();
for (final String string : arrayElementsToFind) {
final int firstIndex = findFirstIndex(listToSeach, string);
if (firstIndex > -1) {
output.append(firstIndex);
} else {
output.append(string);
}
output.append(", ");
}
System.out.println(output);
}
private static int findFirstIndex(final List<String> list,
final String element) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(element)) {
return i;
}
}
return -1;
}
}
Well I suggest this:
List<String> l = new ArrayList<String>();
l.add("test");
l.add("b");
String[] arr = {"test", "c", "b"};
for(int i=0;i<arr.length;++i){
if(l.contains(arr[i]))
s = ""+l.indexOf(arr[i]);
else
s = arr[i];
v = v + s + ",";
}
If got what you saying correct,I think this is less verbose