punxism
punxism

Reputation: 59

How to merge two java object list at once in java

We are using 2 different service. Device name is stored on redis of A service. Device value is stored on mysql of B service.

I think, I can make list of devices on mysql of B service. And I can get device name list at once using redis api.

But how to merge those 2 kind of list object at once? I want to avoid while or for for avoiding performance problem.

I use JDK7.

Thanks

=====================================

My question is how to merge two object, not list.

Class Device {
    Integer id;
    String deviceName;
    List deviceValues;
}

I can get id and devicesValues on Mysql. I can get deviceName from redis

If I get below objects how to merge it?

List<Device> devices = getFromMysql(); //deviceName is null
List<String> deviceNames = getFromRedis();

How to merge devices & devicenames?

Upvotes: 1

Views: 5169

Answers (3)

Anonymous Coward
Anonymous Coward

Reputation: 3200

You are asking for a merge, which I understand as meaning that if an element is common to both lists the resulting list should have it once.
Sets are a good way to to this.

 Set<String> set = new HashSet<>( (listOne.size()+listTwo.size()) * 2 );
 set.addAll(listOne);
 set.addAll(listTwo);
 List<String> newList = new ArrayList<>();
 newList.addAll( set );

Also note that although you want to avoid for or while that is not really possible. This code, and any other, is only hiding them. The implementation of addAll will have a loop in one way or another.
It is a good idea though to let the API manage those loops since they are likely to be better optimized for each platform. Rather than doing them yourself.
But even more important than optimizing loops is to use proper structures. Trying to do a merge with List will take way longer than with a HashSet.

Upvotes: 0

Shiladittya Chakraborty
Shiladittya Chakraborty

Reputation: 4418

 List<String> newList = new ArrayList<String>();
 newList.addAll(listOne);
 newList.addAll(listTwo);

Other Option :

 List<String> newList = new ArrayList<String>(listOne);
 newList.addAll(listTwo);

Where listOne is the first list and listTwo is the second list. Instead of type String you can use any type as per your requirement.

Upvotes: 1

Rahul Tripathi
Rahul Tripathi

Reputation: 172578

If you are using Apachecommon then

ListUtils.union(list1,list2);

You can also look for Iterables.concat( .. )

Combines multiple iterables into a single iterable. The returned iterable has an iterator that traverses the elements of each iterable in inputs. The input iterators are not polled until necessary. The returned iterable's iterator supports remove() when the corresponding input iterator supports it.

Upvotes: 0

Related Questions