Java list minus list

Subtracting Lists in Java 8 using the Minus Operation

To eliminate an element, one can either scan the entire List in list implementations or calculate the hash code and locate the target bucket in a HashSet. Alternatively, if Apache common is being used, one can use ListUtils to subtract the elements in the second list from the first list and store the outcome in a new list.

Minus operation in java 8 for subtracting Lists

List diff = list1.stream() .filter(item -> !list2.contains(item)) .collect(Collectors.toList()); 
List difference = new ArrayList<>(list1); difference.removeAll(list2); System.out.println("Remove: " + difference); //3 
CollectionUtils.subtract(list1, list2); 

Advantageous: Highly legible. Drawback: Absence of type security.

Minus operation in java 8 for subtracting Lists, List difference = new ArrayList<> (list1); difference.removeAll (list2); System.out.println («Remove: » + difference); //3. Implementation is correct but this is not intersection. This is subtraction. Intersection should result into common elements between two Sets. Code sampleList diff = list1.stream().filter(i -> !list2.contains(i)).collect (Collectors.toList());Feedback

Perform Subtraction on list items in java

I am not entirely sure about your requirements, but it appears that you wish to deduct the values of certain indexes from your List.

List all=new ArrayList(); List al2=new ArrayList(); al2.add(rs.getDouble(10)); al2.add(rs.getDouble(11)); all.add(rs.getDouble(11)); for(int i=0;iy) < //check to avoid negative subtractions result z=x-y; >else < z=y-x; >System.out.println(z); // do something with the result i am just printing it out > 

How to subtract values of two lists/arrays in Java?, Always do it in steps. Take your problem for example. You need to subtract values from 2 arrays with values. int [] list1 = <4,2,1>; int [] list2 = ; Now you have 2 list. Ok next step, write a loop to go through the list. But first make sure that both list have the same length or else you will get an index out of …

Subtracting one arrayList from another arrayList

Is there any particular obstacle that prevents you from utilizing List.removeAll(List)?

 List one = new ArrayList(); one.add(1); one.add(2); one.add(3); List two = new ArrayList(); two.add(0); two.add(2); two.add(4); one.removeAll(two); System.out.println(one); result: "[1, 3]" 

Consider utilizing the subtract method from the CollectionUtils class of org.apache.commons.collections.

The returned Collection will contain the difference of a and b. For each element e in the new Collection, its cardinality will be the difference between the cardinality of e in a and the cardinality of e in b. If this difference is negative, the cardinality will be set to zero.

CollectionUtils.subtract(java.util.Collection a, java.util.Collection b) 

From Apache Commons Collections

Java 8

List list1 = Arrays.asList(1, 2, 3); List list2 = Arrays.asList(1, 2, 4, 5); List diff = list1.stream() .filter(e -> !list2.contains(e)) .collect (Collectors.toList()); // (3) 

The original list remains unchanged with this answer. To modify the original list, we have the option of using remove . Additionally, forEach can also be used, which is the default method in Iterator , or we can use a stream with a filter.

Using ListUtils

In case of Apache common usage, an alternative would be to utilize ListUtils .

ListUtils.subtract(list, list2) 

The second list elements are subtracted from the first list and stored in a new list, where the cardinality is maintained. Unlike List.removeAll(Collection) , if the first list has two instances of null and the second list has only one, the resulting list will still have one instance of null .

Perform Subtraction on list items in java, ref.diff () is the method where difference between two list is calculated and when I use Источник

List minus List

I have following code. In the first i tried to set values in the list called ‘unavailable’. Next, in the for each I have to produce a cycle on the list domainStr minus unavailable. How can i do it?

public Result execute(List domainsStr) < Result result = new Result(); try < Listdomains = domainService.findByNames(domainsStr); result.setUnavailable(domains); > catch (Exception e) < logger.error(e.getMessage(), e); >for (String domain : domainsStr) < . >return result; > public static class Result < private Listunavailable = new ArrayList<>(); public List getUnavailable() < return unavailable; >public void setUnavailable(List unavailable) < this.unavailable = unavailable; >> 

user3127896

2 Answers

removeAll(Collection c) is the function which would be the most helpful to you. Having said that, this will work properly only if you have the equals method correctly defined for your Domain object. In this case it is a String so it doesnt matter. But, just to keep it in mind.

so just say, domainsStr.removeAll(result.getUnavailable());

Also, if the Result class is static, why the new object creation here?

Result result = new Result(); 

This result.setUnavailable(domains); can be changed to Result.setUnavailable(domains);

Hrishikesh Avatar

answered Jan 14 ’23 06:01

Hrishikesh

I have to to produce a cycle on the list domainStr minus unavailable.

If I understood correctly, I think you are looking for the removeAll method :

Removes from this list all of its elements that are contained in the specified collection (optional operation).

domainsStr.removeAll(result.getUnavailable()); for (String domain : domainsStr)

If you want to let domainsStr unchanged, you can create a temporary list and perfom these operations on it.

Источник

Вычитание одного arrayList из другого arrayList

у меня есть два arrayLists, и я пытаюсь «вычесть» один arrayList из другого. Например, если у меня есть один arrayList [1,2,3], и я пытаюсь вычесть [0, 2, 4], результирующий arrayList должен быть [1,3].

List a = new ArrayList<>(Arrays.asList(1, 2, 3)); List b = Arrays.asList(0, 2, 4); subtract(a,b) // should return [1,3] 
//returns a new IntSet after subtracting a from b // .minus().toString() ArrayList minusArray = new ArrayList(); minusArray.addAll(array1); for(int i =0; i < minusArray.size(); i++)< for(int j = 0; j < array2.size(); j++)< if(minusArray.get(i).equals(array2.get(j)))< minusArray.remove(i); if(i == 0)< ; >else if(j == 0) < ; >else < i = 0; j = 0; >> else<> > > return minusArray; 

мой код работает в некоторых случаях, например, если arrayList1 = [4,6] и arrayList2 = [6] это даст мне результат [4] . Но если я попробую что-то вроде [1,2,4] и [0,4,8]

java.lang.IndexOutOfBoundsException: Index: 2, Size: 2 at java.util.ArrayList.rangeCheck(Unknown Source) at java.util.ArrayList.get(Unknown Source) at IntSet.minus(IntSet.java:119) at IntSetDriver.main(IntSetDriver.java:62) 

вот код, который я придумал. Я сделал тестовые прогоны через него, и мне кажется, что он должен работать. Пользователь вводит эти arrayLists и они пресортированы, я также не знаю хэша или big-O.

ArrayList minusArray = new ArrayList(); minusArray.addAll(array1); for(int i =0; i < minusArray.size(); i++)< for(int j = 0; j < array2.size(); j++)< if(minusArray.get(i).equals(array2.get(j)))< minusArray.remove(i); >else<> > > return minusArray; 

8 ответов

ваша проблема в том, что в вашем minusArray.снимать.(..) вызов вы можете уменьшить размер minusArray. Чтобы исправить это, начните с array.size () — 1 и обратный отсчет до 0

проверьте это-даже это не исправит его. Вам нужно изменить порядок ваших петель

есть ли причина, по которой Вы не можете просто использовать List.removeAll (список)?

 List one = new ArrayList(); one.add(1); one.add(2); one.add(3); List two = new ArrayList(); two.add(0); two.add(2); two.add(4); one.removeAll(two); System.out.println(one); result: "[1, 3]" 

попробуйте использовать метод вычитания org.апаш.палата общин.коллекции.Класс CollectionUtils.

возвращает новую коллекцию, содержащую a-b. Мощность каждого элемента e в возвращаемой коллекции будет равна мощности e в A минус мощность e в b или нулю, в зависимости от того, что больше.

CollectionUtils.вычесть (java.утиль.Коллекция a, java.утиль.Коллекция b)

пересекая minusArray с помощью индекса-это один из способов сделать это, но я предлагаю вам использовать contains(Object) метод, который позволит вам использовать remove(Object) для конкретного элемента array2 .

конечно, всегда есть removeAll(Collection) что делает почти все, что нужно.

вы можете использовать org.апаш.палата общин.коллекции.ListUtils и сделать все, что вы хотите только одну строку =)

List resultList = ListUtils.subtract(list, list2); 

на всякий случай, если вы планируете использовать Java8, вы также можете использовать потоки:

List list1 = Arrays.asList(1, 2, 3); List list2 = Arrays.asList(1, 2, 4, 5); List diff = list1.stream() .filter(e -> !list2.contains(e)) .collect (Collectors.toList()); // (3) 

этот ответ не манипулирует исходным списком, и если это намерение, мы можем использовать remove . Также мы можем использовать forEach (способ по умолчанию в Iterator ) или поток с фильтра.

Я предполагаю, что вы получаете проблему диапазона, потому что вы исключили один из элементов, который изменяет то, что ищет внутренний цикл (я знаю, что эта проблема возникает при работе с обычными списками и коллекциями).

то, что мне приходилось делать в прошлом, чтобы обойти это, — это создать список элементов, которые необходимо удалить (то есть те, которые находятся в исходном списке). Повторите этот новый список и непосредственно удалите элементы исходного списка без необходимости пусть итератор пройдет через него.

попробуйте этот ответ если removeAll() Не то, что вы хотите. например, если вас интересует что-то вроде вычисление разности двух списков с дубликатами

вычесть (a, b)

такое предложение исполнителей Guava о том, как реализовать вычитание

«создать ArrayList, содержащий a, а затем вызовите remove для каждого элемента в b.»

разница в removeAll ()

[1,2,2,3].removeAll([1,2,3]) //is empty [1,2,3].forEach((i)->[1,2,2,3].remove(i)); //a is [2] 

Источник

Читайте также:  Php file exists null
Оцените статью