Remove Alternate Elements from ArrayList in Java 7

huangapple go评论73阅读模式
英文:

Remove Alternate Elements from ArrayList in java 7

问题

我有一个包含以下元素的字符串数组:

5.0,99,5.5,100,6.0,101

现在我想要做的是,我需要删除所有以字符串格式表示的小数值,如 5.05.56.0

所以我的最终数组应该包含元素 99100101

我到目前为止所做的如下所示:

public static String[] deleteElement(String[] str_array) {
		//String[] str_array = {"item1","item2","item3"};
		List<String> list = new ArrayList<String>(Arrays.asList(str_array));
		
		list.remove("5.0");
		list.remove("5.5");
		list.remove("6.0");
		return str_array = list.toArray(new String[0]);
	}

我已经硬编码了这些值,这是相当不好的做法,因为未来的值可能会超过当前的值,所以我希望能够通过使用 index 来删除。

我已经尝试过使用 remove(index) 来删除,还尝试过使用偶数索引位置,如 0、2、4,但实际发生的情况是,在删除 5.0 之后,元素被向左移动,所以 100 进入第二个位置,然后在下一次迭代中被删除。

所以是否有一种方式可以构建一个通用函数,以便如果小数值中有更多元素,也可以被删除。

注意
字符串小数值始终位于偶数索引位置。

英文:

I have an array of String containing below elements

5.0,99,5.5,100,6.0,101

Now what I want to do I need to remove all the decimal value in string format like 5.0,5.5 and 6.0

so my final array should contain elements 99,100,101

so what I'd done so far is show in below code

public static String[] deleteElement(String[] str_array) {
		//String[] str_array = {"item1","item2","item3"};
		List<String> list = new ArrayList<String>(Arrays.asList(str_array));
		
		list.remove("5.0");
		list.remove("5.5");
		list.remove("6.0");
		return str_array = list.toArray(new String[0]);
	}

I have hardcoded the values which is quite bad practice as the values in future may be more than the current values, so I want a way to remove by using index.

I have tried to remove using remove(index) also, using even index positioning like 0,2,4,but what actually happening is, after deletion of 5.0 , elements are shifted left side, so 100 comes into the 2nd position, and in next iteration 100 deleted.

So is there any way where I can construct a generic function so if there are more elements in decimal value so it can also be deleted.

NOTE:
The string decimal values will always be residing on even index positioning.

答案1

得分: 2

以下是翻译好的代码部分:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class DecimalRemoval {
    public static void main(String[] args) {
        
        List<String> lst = Arrays.asList("5.0","99","5.5","100","6.0","101");
        List<String> resultant = new ArrayList<>(lst.size());
        
        for(String element: lst) {
            if(! element.contains("."))
                resultant.add(element);
        }
        
        System.out.println(resultant);
    }
}
英文:

You can go with the below approach, it worked fine for me !!

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class DecimalRemoval {
	public static void main(String[] args) {
		
		List&lt;String&gt; lst = Arrays.asList(&quot;5.0&quot;,&quot;99&quot;,&quot;5.5&quot;,&quot;100&quot;,&quot;6.0&quot;,&quot;101&quot;);
		List&lt;String&gt; resultant = new ArrayList&lt;&gt;(lst.size());
		
		for(String element: lst) {
			if(! element.contains(&quot;.&quot;))
				resultant.add(element);
		}
		
		System.out.println(resultant);
	}
}

Remove Alternate Elements from ArrayList in Java 7

Also attaching the screenshot from my workspace.

答案2

得分: 2

我们已经从 list.size() - 1 遍历到 0 的位置,这样数字就不会被推到最前面。
当你从 0 遍历到 列表的大小,然后如果你删除一个元素,会跳过一个元素,因为列表的 size() 减小了,而 i 保持增加。
例如:["5.0","6.1","5.5","100","6.0","6.6"]
当你从 0 遍历到 size() - 1
i = 0:
看到并移除了 5.0,然后列表变为 ["6.1","5.5","100","6.0","6.6"],现在 6.1 在索引 0 处。

i = 1:
移除了 5.5,然后列表变为 ["6.1","100","6.0","6.6"],现在 100 在索引 1 处。

依此类推。

但是,当从 size-1 遍历到 0 时,将会移除每个单独的元素,而不用担心遗漏任何小数点后的数字。
自己尝试一下,你就会明白为什么它能正常工作,以及为什么从 0n-1 不起作用。

            String arr[] = {"5.0","99","5.5","100","6.0","101"};
            List<String> list = new ArrayList<String>(Arrays.asList(arr));
            for(int i = list.size() - 1 ; i >= 0 ; i--) {
            	String number = list.get(i);
            	if(number.contains(".")) {
            		list.remove(number);
            	}
            }
            
            for(String val : list) {
            	System.out.println(val);
            }

输出:

99
100
101
英文:

We have traversed the List from list.size() -1 to 0<br>
So that number arent pushed in front.<br>
when you traverse it from 0 to size of the list and then if you delete an element 1 element is skipped cause size() of the list decreases and i keeps incrementing.<br>
eg.["5.0","6.1","5.5","100","6.0","6.6"]
when you traverse form 0 to size() - 1<br>
i = 0 : <br>
5.0 is seen and removed and then the list is like [&quot;6.1&quot;,&quot;5.5&quot;,&quot;100&quot;,&quot;6.0&quot;,&quot;6.6&quot;] where now 6.1 is at 0 index.<br>

i = 1: <br>
5.5 is removed and then the list is like<br>
[&quot;6.1&quot;,&quot;100&quot;,&quot;6.0&quot;,&quot;6.6&quot;] where now 100 is at 1 index.<br>

and so on.<br>

But when traverse from size-1 to 0 it will remove every single element without the fear of missing any decimal number.<br>
Try this on your own and you will get to know why it is working and why 0 to n-1 isn't working.

            String arr[] = {&quot;5.0&quot;,&quot;99&quot;,&quot;5.5&quot;,&quot;100&quot;,&quot;6.0&quot;,&quot;101&quot;};
            List&lt;String&gt; list = new ArrayList&lt;String&gt;(Arrays.asList(arr));
            for(int i = list.size() - 1 ; i &gt;= 0 ; i--) {
            	String number = list.get(i);
            	if(number.contains(&quot;.&quot;)) {
            		list.remove(number);
            	}
            }
            
            for(String val : list) {
            	System.out.println(val);
            }

output:

99
100
101

答案3

得分: 2

现有的答案“有效”,但比所需的冗长:

list.removeIf(str -> str.contains("."));
英文:

The existing answers work but are more verbose than required:

list.removeIf(str -&gt; str.contains(&quot;.&quot;));

答案4

得分: 2

你还可以直接流式传递数组并筛选掉不需要的值。

String[] v = {"5.0", "99", "5.5", "100", "6.0", "101"};
v = Arrays.stream(v)
        .filter(str -> !str.contains("."))
        .toArray(String[]::new);

System.out.println(Arrays.toString(v));

输出

[99, 100, 101]
英文:

You can also just stream the array and filter out the unwanted values.

String[] v = {&quot;5.0&quot;,&quot;99&quot;,&quot;5.5&quot;,&quot;100&quot;,&quot;6.0&quot;,&quot;101&quot;};
v = Arrays.stream(v)
        .filter(str-&gt;!str.contains(&quot;.&quot;))
        .toArray(String[]::new);


System.out.println(Arrays.toString(v));

Prints

[99, 100, 101]

</details>



# 答案5
**得分**: 1

一个简单的解决方案可以是:

 1. 实例化一个 `ArrayList<String>`。
 2. 遍历数组,如果元素不包含 `.`,则将其添加到列表中。
 3. 最后将列表转换为数组并返回。

**示例:**

```java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    public static String[] deleteElement(String[] str_array) {
        List<String> list = new ArrayList<>();
        for (String s : str_array) {
            if (!s.contains(".")) {
                list.add(s);
            }
        }

        return list.toArray(new String[0]);
    }

    public static void main(String[] args) {
        // 测试
        System.out.println(Arrays.toString(deleteElement(new String[] { "5.0", "99", "5.5", "100", "6.0", "101" })));
    }
}

输出:

[99, 100, 101]

另外,你也可以按照你已经在做的方式来实现,但这并不是一种高效的方式。因为你首先将所有元素添加到列表中,然后再移除不需要的元素,所以这种方式不如上面建议的方式高效。

public static String[] deleteElement(String[] str_array) {
    List<String> list = new ArrayList<String>(Arrays.asList(str_array));
    for (String s : str_array) {
        if (s.contains(".")) {
            list.remove(s);
        }
    }

    return list.toArray(new String[0]);
}
英文:

A simple solution can be:

  1. Instantiate an ArrayList&lt;String&gt;.
  2. Navigate the array and add the element to the list if it does not contain .
  3. Finally convert the list to an array and return the same.

Demo:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
	public static String[] deleteElement(String[] str_array) {
		List&lt;String&gt; list = new ArrayList&lt;&gt;();
		for (String s : str_array) {
			if (!s.contains(&quot;.&quot;)) {
				list.add(s);
			}
		}

		return list.toArray(new String[0]);
	}

	public static void main(String[] args) {
		// Test
		System.out.println(Arrays.toString(deleteElement(new String[] { &quot;5.0&quot;, &quot;99&quot;, &quot;5.5&quot;, &quot;100&quot;, &quot;6.0&quot;, &quot;101&quot; })));
	}
}

Output:

[99, 100, 101]

Alternatively, you can do it in the way you are already doing but it is not so efficient way. Since you are first adding all the elements to the list and then removing the unwanted ones, therefore it is not so efficient as the one suggested above.

public static String[] deleteElement(String[] str_array) {
	List&lt;String&gt; list = new ArrayList&lt;String&gt;(Arrays.asList(str_array));
	for (String s : str_array) {
		if (s.contains(&quot;.&quot;)) {
			list.remove(s);
		}
	}

	return list.toArray(new String[0]);
}

答案6

得分: 0

对于Java 8用户,最佳解决方案是使用Java lambda表达式。

list.removeIf(element -> element.contains("."));


<details>
<summary>英文:</summary>

 **For Java 8 users ,
 Best solution would be using the Java lambda expressions**.

list.removeIf(element -> element.contains("."));


</details>



huangapple
  • 本文由 发表于 2020年10月10日 22:10:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/64294342.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定