Home > database >  How to use Java Streams to compare two lists and add common to a field
How to use Java Streams to compare two lists and add common to a field

Time:01-13

I have two lists List<Product> products and List<AssetMap> mapAssetIds. Both the Product and AssetMap classes have two fields productId and assetId.

public class Product {
    public String productId;
    public String assetId;
}

public class AssetMap {
    public String productId;
    public String assetId;
}

List<Product> products = new ArrayList<>();
products.add(new Product("pid1", "aid1"));
products.add(new Product("pid2", "aid2"));
List<AssetMap> assetMaps = new ArrayList<>();
assetMaps.add(new AssetMap("pid560", "aid1"));
assetMaps.add(new AssetMap("pid3", "aid3"));

The output should be:

["pid560", "aid2"]

I want to check if the assetIds in products are present in assetIds in mapAssetIds.

If they are, then take the productId from mapAssetIds else take the assetId from Product and put them in a List<String>.

How do I do this using Java Stream?

CodePudding user response:

List<Product> products = new ArrayList<>();
    products.add(new Product("aaa"));
    products.add(new Product("bbb"));
    List<AssetMap> assetMaps = new ArrayList<>();
    assetMaps.add(new AssetMap("bbb"));
    assetMaps.add(new AssetMap("ccc"));

    List<String> commons = products.stream().map(Product::getProductId).collect(Collectors.toList());
    commons.retainAll(assetMaps.stream().map(AssetMap::getAssetId).collect(Collectors.toList()));
    for (String common : commons) {
        System.out.println(common);
    }

output "bbb"

CodePudding user response:

You can do like this:

first create a map from assetMaps so that getAssetId as key and getProductId as value.

Map<String, String> map = assetMaps.stream()
      .collect(Collectors.toMap(AssetMap::getAssetId, AssetMap::getProductId));

then stream over products items and find value based on previous result and in case absent value use default value.

List<String> result = products.stream()
            .map(Product::getAssetId)
            .map(assetId -> map.getOrDefault(assetId, assetId))
            .collect(Collectors.toList());

CodePudding user response:

  List<String> result = new ArrayList<>();
        
        List<String> assestIdsInMap = assetMaps.stream().map(assest -> assest.assestId).collect(Collectors.toList());
        products.stream().forEach(i -> {
            if (assestIdsInMap.contains(i.assestId)) {
                result.add(assetMaps.stream().filter(assetMap -> assetMap.assestId.equals(i.assestId)).findAny().get().productId);
            } else {
                result.add(i.assestId);
            }
        });
  •  Tags:  
  • Related