简体   繁体   English

从 java 中的 ArrayList 中删除替代元素 7

[英]Remove Alternate Elements from ArrayList in java 7

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现在我想做什么,我需要删除字符串格式的所有十进制值,如5.0,5.56.0

so my final array should contain elements 99,100,101所以我的最终数组应该包含元素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 .我对这些值进行了硬编码,这是一种非常糟糕的做法,因为未来的值可能会超过当前值,所以我想要一种使用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.我也尝试使用remove(index) ,甚至使用像 0,2,4 这样的索引定位,但实际发生的是,在删除5.0之后,元素向左移动,所以 100 进入第二个 position,并且在下一次迭代 100 已删除。

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.那么有什么方法可以构造一个通用的 function 所以如果十进制值中有更多元素,那么它也可以被删除。

NOTE : The string decimal values will always be residing on even index positioning.注意:字符串十进制值将始终位于偶数索引位置。

You can go with the below approach, it worked fine for me !!您可以使用以下方法拨打 go,它对我来说效果很好!

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

在此处输入图像描述

Also attaching the screenshot from my workspace.还附上我工作区的屏幕截图。

We have traversed the List from list.size() -1 to 0我们已经遍历了Listlist.size() -10
So that number arent pushed in front.所以这个数字不会被推到前面。
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.当你从0遍历它到size of the list ,然后如果你删除一个元素1元素被跳过导致列表的size()减少并且i不断递增。
eg.["5.0","6.1","5.5","100","6.0","6.6"] when you traverse form 0 to size() - 1例如 ["5.0","6.1","5.5","100","6.0","6.6"] 当你遍历 form 0size() - 1
i = 0:我 = 0:
5.0 is seen and removed and then the list is like ["6.1","5.5","100","6.0","6.6"] where now 6.1 is at 0 index.看到并删除了5.0 ,然后列表类似于["6.1","5.5","100","6.0","6.6"] ,现在6.1的索引为0

i = 1:我 = 1:
5.5 is removed and then the list is like 5.5被删除然后列表就像
["6.1","100","6.0","6.6"] where now 100 is at 1 index. ["6.1","100","6.0","6.6"]现在1001索引处。

and so on.等等。

But when traverse from size-1 to 0 it will remove every single element without the fear of missing any decimal number.但是当从size-1遍历到0时,它会删除每一个元素,而不用担心丢失任何decimal
Try this on your own and you will get to know why it is working and why 0 to n-1 isn't working.自己尝试一下,您就会知道它为什么有效以及为什么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);
            }

output: output:

99
100
101

The existing answers work but are more verbose than required:现有答案有效,但比要求的更冗长:

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

You can also just stream the array and filter out the unwanted values.您也可以只使用 stream 数组并过滤掉不需要的值。

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));

Prints印刷

[99, 100, 101]

A simple solution can be:一个简单的解决方案可以是:

  1. Instantiate an ArrayList<String> .实例化一个ArrayList<String>
  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<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) {
        // Test
        System.out.println(Arrays.toString(deleteElement(new String[] { "5.0", "99", "5.5", "100", "6.0", "101" })));
    }
}

Output: 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<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]);
}

For Java 8 users, Best solution would be using the Java lambda expressions .对于 Java 8 个用户,最佳解决方案是使用 Java lambda 表达式

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM