I've two ArrayList both containing Integer values. My objective is to get identical/common/duplicate values comparing these 2 list. In other words (in SQL parlance), I need the INTERSECT result of two lists, that is, values that appear in both list.
Example:
ArrayList<Integer> list1 = new ArrayList<Integer>();
list1.add(100);
list1.add(200);
list1.add(300);
list1.add(400);
list1.add(500);
ArrayList<Integer> list2 = new ArrayList<Integer>();
list2.add(300);
list2.add(600);
One kind of implementation/solution I could think along is looping one of the list something like:
ArrayList<Integer> intersectList = new ArrayList<Integer>();
for (Integer intValue : list1)
{
if(list2.contains(intValue))
intersectList.add(intValue);
}
In this case, intersectList would contain only 1 Integer item being added, that is 300, which appears in both list.
My question is, are there any better/fastest/efficient way of implementing this logic? Any options available in Apache Commons library?. Any other ideas/suggestions/comments are appreciated.
NOTE: For illustration purpose, I've just shown here 5 items and 2 items being added into the list. In my real-time implementation, there will be more than 1000 elements in each list. Therefore, performance is also a key factor to be considered.
If you're okay with overwriting result for list1:
list1.retainAll(list2);
otherwise clone/copy list1 first.
Not sure on performance though.
list1.retainAll(list2)//for intersection
Use ListUtils from org.apache.commons.collections if you do not want to modify existing list.
ListUtils.intersection(list1, list2)
Related
I have two ArrayList which contains a list of user-defined classes with a large volume of data. One of the lists contains the elements of another list.
I want to filter out the data from list1 which is already present in list2 in a new list3.
I can do this with the help of looping but as the volume of data is very large, I don't want to use looping.
Example:
List<Presentation> presentedDepartmentList //list 1
List<PresentationDetails> excludingDepartmentList //list 2
Both Presentation and PresentationDetails have a common field as
"departmentNumber". I want to filter out the entries in the
"excludingDepartmentList" from the "presentedDepartmentList".
As I am unfamiliar with Java8, I am having difficulty in the task.
Can anyone help me out?
If you filter one collection of size N against a list of size M, the time required will be O(N*M). If M is large, first convert it to a hash set, then your time will be O(N + M).
Set<String> exclusions = excludingDepartmentList.stream()
.map(PresentationDetails::getDepartmentNumber)
.collect(Collectors.toSet());
List<Presentation> filtered = presentedDepartmentList.stream()
.filter(p -> !exclusions.contains(p.getDepartmentNumber()))
.collect(Collectors.toList());
This should do:
List<Presentation> filteredList = presentedDepartmentList.stream().filter(this::shouldBeIncluded).collect(Collectors.toList());
....
public boolean shouldBeIncluded(Presentation presentation) {
!(excludingDepartmentList.stream().filter(a -> presentation.departmentNumber().equals(a.departmentNumber())).findAny().isPresent());
}
Who can help me and give me a code that split an list contains positif and negatif values in two list :the first list contains neagtif values and second list contains positf values without using java library.help me
Why not a little help!
Assuming your List contains integers.
List<Integer> integers = listOfIntegers();
List<Integer> positive = new ArrayList<>();
List<Integer> negative = new ArrayList<>();
for (Integer i : integers) {
if (i >= 0)
positive.add(i);
else
negative.add(i);
}
The next time you need to specify more information. Furthermore, you must ask about a particular problem in your code and not for a complete solution.
I have 2 array list that contain strings:
List1 = [no, yes, ok, not]
List2 = [no, but, vote, check]
Now, how do I compare List1 with List2 and remove the words in List1 if the same word are found in List2. The sorted word(without the same word) are stored in another arraylist.
Outcome should be like this:
List3 = [yes, ok, not]
If you want to store the result in a new list, you need to clone List1 first:
ArrayList list3 = (ArrayList) list1.clone();
or
ArrayList list3 = new ArrayList(list1);
Then use removeAll:
list3.removeAll(list2);
ArrayList provides method to remove all object present in another list.
Refer Removing elements present in collection
In your case list1.removeAll(list2) should solve your problem
You can create third list , add to it your two lists and find in it third list same words. When you find them , delete one.So you'll check your third list with equals().
I suppose you didn't know about the removeAll(Collection c) method present for ArrayLists or just want another way of doing it.
Since you mention that you need to remove the duplicated words from list1, initialize a HashSet and add all the values in list2 to the Set, like so,
Set<String> set = new HashSet<String>();
for(String s: list2)
set.add(s);
Now, do the same with a clone of list1, taking care to remove the strings from list1.
String[] list3 = new String[list1.size()];
list1.toArray(list3);
for(String s: list3)
if(!set.add(s))
list1.remove(s);
This is done in O(n) time, but takes some auxiliary storage. Please let me know if this solved your problem.
I am breaking my mind to find a solution to the following problem.
I have 4 different ArrayList that get their values from a Database.
They can have size from 0 (including) till what ever.
Each list may have different size and values also.
What I am trying to do effectively is :
Compare all the non 0 size lists and check if they have some common integers and what are those values.
Any ideas?
Thank you!
If you need a collection of common integers for all, excluding empty ones:
List<List<Integer>> lists = ...
Collection<Integer> common = new HashSet<Integer>(lists.get(0));
for (int i = 1; i < lists.size(); i++) {
if (!lists.get(i).isEmpty())
common.retainAll(lists.get(i));
}
at the end the common will contain integers that common for all of them.
You can use set intersection operations with your ArrayList objects.
Something like this:
List<Integer> l1 = new ArrayList<Integer>();
l1.add(1);
l1.add(2);
l1.add(3);
List<Integer> l2= new ArrayList<Integer>();
l2.add(4);
l2.add(2);
l2.add(3);
List<Integer> l3 = new ArrayList<Integer>(l2);
l3.retainAll(l1);
Now, l3 should have only common elements between l1 and l2.
You might be wanting to use apache commons CollectionUtils.intersection() to get the intersection of two collections...
Iteratively generate the intersection, and if it is not empty when you are done - you have a common element, and it is in this resulting collection.
Regarding empty lists: just check if its size() is 0, and if it is - skip this list.
You can do this. If you have multiple elements to search, put the search in a loop.
List aList = new ArrayList();
aList.add(new Integer(1));
if(aList !=null && !aList.isEmpty()) {
if(aList.contains(1)) {
System.out.println("got it");
}
}
I have 9 different ArrayList and I want to have a list of the top 5.
I'm thinking of sorting those ArrayLists by their sizes.
Is it possible to do that? If so, how can I achieve that?
After a few try i finally got it working, just want to share it with everyone.
it will be better to get the size of the arraylist and add it to the big arraylist
// creates an ArrayList that holds ArrayLists
List allTheLists = new ArrayList();
allTheLists.add(pbaustraliaList.size());
allTheLists.add(pbotherList.size());
allTheLists.add(pbunitedStatesList.size());
allTheLists.add(pbunitedKingdomList.size());
allTheLists.add(pbchinaList.size());
allTheLists.add(pbgermanyList.size());
allTheLists.add(pbindiaList.size());
allTheLists.add(pbjapanList.size());
allTheLists.add(pbsingaporeList.size());
Comparator comparator = Collections.reverseOrder();
Collections.sort(allTheLists,comparator);
//display elements of ArrayList
System.out.println("ArrayList elements after sorting in descending order : ");
for(int i=0; i<allTheLists.size(); i++) {
System.out.println(allTheLists.get(i));
}
What you could do is the following:
// this List of lists will need to contain
// all of the ArrayLists you would like to sort
List<ArrayList> allTheLists;
Collections.sort(allTheLists, new Comparator<ArrayList>(){
public int compare(ArrayList a1, ArrayList a2) {
return a2.size() - a1.size(); // assumes you want biggest to smallest
}
});
This will sort the list of lists by the length of each list. The first element in the sorted list will be the longest list, and the last one will be the shortest list.
Then, you can iterate through the first 5 lists to see what the top 5 were.
Some links for reference:
Sorting tutorial
Collections Javadoc
Comparator Javadoc
Depending on how you have your ArrayLists stored, the code to create a List<ArrayList> would look something like this:
// creates an ArrayList that holds ArrayLists
List<ArrayList> allTheLists = new ArrayList<ArrayList>();
allTheLists.add(yourList1);
allTheLists.add(yourList2);
...
allTheLists.add(yourList9);
you can do like this as well
public static <T> List<List<T>> sort(List<List<T>> list) {
list.sort((xs1, xs2) -> xs1.size() - xs2.size());
return list;
}
The sort method that's available on a List needs a Comparator. That comparator can be created with the Comparator.comparing method, with additional special implementations including for extracting and comparing an int - Comparator.comparingInt.
import static java.util.Comparator.comparingInt;
...
List<List<Integer>> listOfLists = ...
listOfLists.sort(comparingInt(List::size));
List::size will map a List to an int (the size of the list) and use that to create a new Comparator that can be used for our sorting purposes.
If you want largest first
listOfLists.sort(comparingInt(List::size).reversed());
Dump the top 5 (switching over to Java 8 streams):
listOfLists.stream()
.sorted(comparingInt(List::size).reversed())
.limit(5)
.forEachOrdered(System.out::println);