How to exclude certain elements from a List
I have a List with the following elements.
List<String> numbers = new ArrayList<String>();
numbers.add("1");
numbers.add("2");
numbers.add("3");
How do I get a subset of the List开发者_StackOverflow中文版 without say "1"
? Is there a simpler function which will work against a List of any type.
The question is ambiguous.
numbers.remove("1");
will remove the first instance of "1" in any list. If you might have duplicate elements, use numbers.removeAll (Collections.singletonList ("1"));
to remove all of them.
If on the other hand you want to get a subrange of the list, use the subList
method.
I think this could help you out:
final List<String> numbers = Arrays.asList("1", "2", "3");
final List<String> filtered = numbers.stream()
.filter(num -> !"1".equals(num))
.collect(Collectors.toList());
You could use Guava to create a filtered Collection
view:
Collection<String> filtered = Collections2.filter(numbers,
Predicates.not(Predicates.equalTo("1")));
That's a live view of the original List
, so it's very efficient to create but might not be efficient to use depending on how you need to use it and how small the filtered collection is compared to the original. You can copy it to a new list if that will work better:
List<String> filteredList = Lists.newArrayList(filtered);
The simplest way to create a copy list containing all elements except the one you don't want is to use a simple for
loop:
List<String> copy = new ArrayList<String>();
for (String number : numbers) {
if (!"1".equals(number))
copy.add(number);
}
If you want to modify the original list instead, numbers.removeAll
is what you want (as mentioned by @Robin Green).
you can take a look at Guava libraries which has a filter method on any collection type.
here are some examples for your reference.
If you don't want to use third party libraries, you have to manually iterate the list and need to copy the elements which doesn't match your criteria.
List.subList(int fromIndex, int toIndex)
Edit: Possible that I didn't understand the question.
@Op. Do you want to remove items of a certain value, or do you want to have a view between two indices?
Yes, for example to remove the 1
(s) from the list you could do:
int i = 0;
while((i = numbers.indexOf("1")) > -1) {
numbers.remove(i);
}
You can do this with a list of objects, too, or a filtering criterion.
Edit: There will only be one and not many? Then just do:
int i = 0;
if((i = numbers.indexOf("1")) > -1) {
numbers.remove(i);
}
From Java8 onward, stream api can be used, for example:
final List<String> list = Arrays.asList("1", "2", "3", "4", "5");
final List<String> listToExclude = Arrays.asList("2", "3");
final List<String> filtered = list.stream()
.filter(item -> !listToExclude.contains(item))
.collect(Collectors.toList());
System.out.println(filtered); // returns {"1", "4", "5"}
精彩评论