i have two arraylist one have employee entity list other also have same entity list.
one Arraylist have all employees and other one have selected employees.
now i want to arrange employee in list in first Arraylist as on selected employees first arrive which is in second arraylist.
for Ex::
list1 [{1,test1}{2,test2},{3,test3},{4,test4}]
list2[{2,test2}{4,test4}]
what i want is
list1[{2,test2}{4,test4}{1,test1}{3,test3}]
How can i do this same by using single method or minimal line code ..
From what you have said it seems like you just need to take the members of list1 that are not in list2 and append them to list2 in the order they appear in list1.
Something like:
for ( Employee e : list1 ) {
if ( !list2.contains(e) ) {
list2.append(e);
}
}
Why not use Collections.sort(list1, yourComparator) where yourComparator sorts the entries in list1 as you need?
You could use Apache CollectionUtils like this:
CollectionUtils.addAll(list2, CollectionUtils.subtract(list1, list2));
You don't even need a loop or a comparator. Just use the Collections API!
Firstly, you want a LinkedHashSet - preserves uniqueness and order
Use the API to add list2, then list2, then populate a list with the set:
Here's an example using Integers:
// Set up your data
List<Integer> l1 = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4, 5));
List<Integer> l2 = new ArrayList<Integer>(Arrays.asList(2, 5));
// Here's the 3 lines that do the work
Set<Integer> set = new LinkedHashSet<Integer>(l2);
set.addAll(l1);
List<Integer> l3 = new ArrayList<Integer>(set);
// All done
System.out.println(l3); // "[2, 5, 1, 3, 4]"
Related
I have two lists, in one list values are 1,2,3
another list 2,3
I want to remove the values which are not matched in both lists.
2 and 3 are matched in both lists then 1 is not mached in both lists so I want to remove that value.
List original = [1,2,3];
List dummy = [2,3];
If it's possible to use sets instead, then you can just get the intersection between the sets (info):
Set<String> s1;
Set<String> s2;
s1.retainAll(s2); // s1 now contains only elements in both sets
Of course with sets you can't have duplicates and you'll lose ordering.
You don't need to use a Set to achieve your requirement.
Use retainAll() defined in Collection that any List implementation implements such as :
List<Integer> original = new ArrayList<>(Arrays.asList(1,2,3));
List<Integer> dummy = Arrays.asList(2,3);
original.retainAll(dummy);
System.out.println(original);
Output :
[2, 3]
If you are using Java 8+ you can use :
original.removeIf(a -> !dummy.contains(a));
Here is an example with Java 10
var original = new ArrayList<>(List.of(1, 2, 3, 4));
var dummy = new ArrayList<>(List.of(2, 4, 3));
original.removeIf(a -> !dummy.contains(a));
System.out.println(original);
->[2, 3, 4]
I have two lists.
List<Integer> list1 = new ArrayList<>(Arrays.asList(1, 2, 2));
List<Integer> list2 = new ArrayList<>(Arrays.asList(2, 3, 4));
I want to remove the elements contained in list2 from list1, precisely as many times as they are contained in list2. In the example above: when we remove elements in list 1 which exist in list 2, we should get as result [1, 2] (only one occurrence of 2 should be removed from list1 because list2 contains only one instance of 2).
I tried with list1.removeAll(list2); but I got as result list containing only [1].
What is the best way to achieve this? Iterate through both lists simultaneous seems a bit ugly for me.
If I understand correctly, you only want to remove a single 2 element from list1 rather than all of them. You can iterate over list2 and attempt to remove each element from list1. Keep in mind that there are more efficient methods than this if list2 cannot contain duplicates.
var list1 = new ArrayList<>(List.of(1, 2, 2));
var list2 = List.of(2, 3, 4);
list2.forEach(list1::remove);
list1 now contains the following:
[1, 2]
See starman1979's answer for the same solution, but using a lambda rather than a method reference.
How about:
list2.forEach(i -> {
list1.remove(i); //removes only first occurrence - if found
});
list1 now contains
[1, 2]
Given
List<Integer> a = new ArrayList<>(Arrays.asList(1, 2, 2));
List<Integer> b = Arrays.asList(2, 3, 4);
Use one of the following variants to get the desired result:
1. Plain java
b.forEach((i)->a.remove(i));
a now contains
[1, 2]
Give credit at original post: add +1:
2. Apache Commons
In apache commons there is a subtract method
Collection<Integer> result = CollectionUtils.subtract(a, b);
result now contains
[1, 2]
Here is how they implemented it
3. Guava
Since guava doesn't offer a subtract method you may find this advice from the google implementors helpful
"create an ArrayList containing a and then call remove on it for each element in b."
Which basically renders to what was already mentioned under 1.
I am having a list in the format
ArrayList<Integer> list = new ArrayList();
where I add and remove various elements in a loop. However, I need some structure where I can store the temporary lists so that I can access them later.
So for example, if I do System.out.print(list) it will return
[1,2,3,4]
then I need to call something like store.add(list)
and then if I add another element to the list - list.add(5) it becomes
[1,2,3,4,5]
then again
store.add(list)
and by calling System.out.print(store) it should return
[1,2,3,4]
[1,2,3,4,5]
In other words, store should be something like list within list?
List in list creating like this: List<List<Integer>> listInList = new ArrayList<List<Integer>>();
I suppose you want to have multiple versions of the same list.
You can't get that by just having a List of List.
The list will store only reference to the member lists stored inside it. So when you edit your list, all older versions will be edited as well. It's the same list behind the scene.
The correct way to use the List<List<Integer>> would be as follows.
List<List<Integer>> store = new ArrayList<>(); // Create storage for versions
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4));
store.add(new ArrayList<>(list)); // Add list's copy to store.
list.add(5); // Edit it as you want.
store.add(new ArrayList<>(list)); // Add list's copy to store.
System.out.println(store); // Print all versions
Output:
[[1, 2, 3, 4], [1, 2, 3, 4, 5]]
Hope this helps.
It is somewhat wasteful to store every new list, especially when the changes to the previous are very simple (e.g. additions and deletions at/from the end). You could come up with a strategy of keeping track of changes rather than storing the same information repeatedly.
First, you should decide which of the following is more important:
Have the list of lists readily available, at the expense of memory. This is desirable when you know you will need it very often and therefore cannot afford the overhead of generating it on-the-fly from history.
Use space efficiently, at the occasional cost of computing the list of lists from history. This is desirable when you make many changes and use the list of lists rarely.
The solutions already posted address 1., so here is a proposal for 2. (I will restrict the possible operations to adding and removing from the rear for the sake of brevity):
public enum Operation { ADD, REMOVE }
public class Modification {
Operation operation;
Integer element;
public Modification(Operation operation, Integer element) {
this.operation = operation; // could add some sanity checks (e.g. cannot remove from empty list)
this.element = element;
}
}
List<Integer> initialList = Arrays.asList(1, 2, 3, 4);
List<Modification> history = new ArrayList<>();
history.add(new Modification(Operation.ADD, 5));
Then you can define a function to compute the list of lists that you need:
List<List<Integer>> getAllLists (List<Integer> initialList, List<Modification> history) {
List<List<Integer>> allLists = new ArrayList<>();
allLists.add(initialList);
prevList = initialList;
for (Modification modification : history) {
prevList = new ArrayList<>(prevList);
if (modification.operation == ADD) prevList.add(modification.element);
else prevList.remove(prevList.size()-1);
allLists.add(prevList);
}
return allLists;
}
i got two Lists with integer IDs an old list and a new list.
Now i want to do three steps:
1. Check which IDs from (old)List1 are also found in (new)List2
2. Delete all elements from List1 that are not found in List2 after step 1
3. Add all missing IDs from List 2 to List 1
I was thinking of adding two boolean arrays and set a flag when an element was found, later i could delete the IDs elements from List1 and add the unchecked IDs from List2 in List1.
Maybe there are better ways?
Try it this way:
List<Integer> list1 = new ArrayList<>(Arrays.asList(1, 2, 3, 4));
List<Integer> list2 = new ArrayList<>(Arrays.asList(2, 3, 5, 6));
list1.retainAll(list2);
list2.removeAll(list1);
list1.addAll(list2);
System.out.println(list1);
OUTPUT:
[2, 3, 5, 6]
put all content in a lookup table, for instance use a HashSet.
I have an hash map, which maps integers to array of ArrayLists. For example, my data structure is the following:
7->((7,5,**4,3,1**),(7,6,4,3,1))
4->((4,2,1),(4,3,1))
Here, 7 is key, and arraylist e.g is (7,5,4,3,1), the array of arraylist in turn is ((7,5,4,3,1),(7,6,4,3,1))
4 is key, and arraylist e.g. is (4,2,1), the array of arraylist in turn is ((4,2,1),(4,3,1))
I wish to substitute the key values (in any given arraylist) and the values following it to create other arraylists, one example of this is given below:
7->((7,5,**4,2,1**),(7,6,4,2,1),(7,5,4,3,1),(7,6,4,3,1))
the thing I am not getting is how to obtain this substitution....to create bigger arraylists
the thing I am not getting is how to obtain this substitution....to create bigger arraylists..i know the datastructure..but want to create arraylists by substitution as given in subsequent example
Is there someway in java programming by which I may achieve this?
I am a novice at Java programming...I thought long about this but could not move it...can someone please help
HashMap<Integer,ArrayList<ArrayList<Integer>>> map;
map = new HashMap<Integer,ArrayList<ArrayList<Integer>>>();
EDIT: I've used 2 lines so that my answer could be more readable.
What actually do you want?
Is bellow code helpful?
Map<Integer, List<List<Integer>>> mapData = new HashMap<Integer, List<List<Integer>>>();
public void fillData(List<List<Integer>> lists)
{
// provide any kind of list of list
// e.g lists = {2,3,5,3}, {4,5,3,2}, {2,4,3}, {6,3,4}
for(List<Integer> list : lists)
{
int mapKey = list.get(0);
if(mapData.get(mapKey) == null)
{
// list of list will be null in first occurence of key(first element of list).
// create list of list and put tat in map.
List<List<Integer>> tempListOfList = new ArrayList<List<Integer>>();
tempListOfList.add(list);
mapData.put(mapKey, tempListOfList);
}
else
{
// from second occurence of same key.
// put list in the list of list of that key.
List<List<Integer>> listOfListInMap = mapData.get(mapKey);
listOfListInMap.add(list);
}
}
}
public List<List<Integer>> getListsByKey(int key)
{
// get list of list by mapKey
return mapData.get(key);
}
HashMap<Integer, ArrayList<ArrayList<Integer>>>.
below should do it:
Map<Integer, ArrayList <ArrayList<Integer>>> map = new hashMap<>();
Consider using a List of Lists and store this as part of a Map data structure. One possible way would be as follows:
Map<Integer,List<List<Integer>>> map = new HashMap<Integer, List<List<Integer>>>();
//How to add
List<List<Integer>> list = map.get(your_key);
if(list == null){ //This should be for the first time you're accessing the map with the key
list = new ArrayList<List<Integer>>();
}
//Create a inner list which will store the list of numbers
ArrayList<Integer> innerList = new ArrayList<Integer>();
innerList.add(integer_values);
//Add inner list to the list of lists
list.add(innerList);
//Finally put the list of list into the map with the key
map.put(your_key, list);
Edit: Assuming you know index of the list where you want to add new elements:
//Adding numbers to the inner list - assume you know the index
List<List<Integer>> list = map.get(key);
if(list == null || list.size() >= index){ //There's no list against the key or the size of the list is less then the index requested
return;
}
//Add new elements to the inner list
List<Integer> innerList = list.get(index);
innerList.add(your_new_int_values);
//Add inner list to the list of lists
list.add(innerList);
//Finally put the list of list into the map with the key
map.put(key, list);
You want to map integers to a list of lists of integers. This can be declared as:
Map<Integer, List<List<Integer>>> map = new HashMap<List<List<Integer>>>();
You can then put instances of ArrayList<List<Integer>> (or any other class that implements List) and for each such list of lists, you can add instances of ArrayList<Integer>.
You can then use the List.subList() method to put selected sublists into other entries in the map.
Say you have a list containing the two lists (7,5,4,3,1) and (7,6,4,3,1) stored under 7 and you want to construct the list of lists that should be stored under the key 4. You can do this:
List<List<Integer>> sevens = map.get(7);
List<List<Integer>> fours = new ArrayList<List<Integer>>();
for (List<Integer> aSevenList : sevens) {
int index = aSevenList.indexOf(4);
if (index >= 0) {
fours.add(aSevenList.subList(index, aSevenList.size()));
}
}
map.put(4, fours);
If you want to substitute one list as part of another, the following code fragment shows how that might be done:
int[] vals = { 7, 6, 5, 4, 3, 2, 1 };
List<Integer> list = new ArrayList<Integer>();
for (int val : vals) list.add(val);
List<Integer> sub = new ArrayList<Integer>();
sub.add(40);
sub.add(30);
sub.add(20);
System.out.println("Original list: " + list);
List<Integer> slice = list.subList(3, vals.length - 1);
slice.clear();
slice.addAll(sub);
System.out.println("Modified list: " + list);
This will generate the following output:
Original list: [7, 6, 5, 4, 3, 2, 1]
Modified list: [7, 6, 5, 40, 30, 20, 1]
Note that changes to a sublist are propagated to the original list.