0

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 ..

1
  • I do not have overwrite equals method..so i can't use contains property of collections. and i have list of Employees so it would be like list<Employee> Commented Jul 1, 2011 at 13:29

4 Answers 4

3

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);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Why not use Collections.sort(list1, yourComparator) where yourComparator sorts the entries in list1 as you need?

Comments

1

You could use Apache CollectionUtils like this:

CollectionUtils.addAll(list2, CollectionUtils.subtract(list1, list2));

2 Comments

Why take a sledgehammer to crack a nut?
For the 'minimal code' requirement. However, if they're not already using it, it might indeed be overhead to include CollectionUtils for this.
0

You don't even need a loop or a comparator. Just use the Collections API!

  1. Firstly, you want a LinkedHashSet - preserves uniqueness and order
  2. 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]"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.