2015-08-06 26 views
5

tarafından Haritaya, RUR vb EURO, ABD DolarıJava 8 toplayın iki Listeler bir nesne var koşulu

Ve İki liste

List<CurrencyItem> currenciesByCommercialBank = ... 
List<CurrencyItem> currenciesByCentralBank = ... 

Bu listeleri, currenciesByCommercialBank anahtarlarının bulunduğu Map<CurrencyItem, CurrencyItem> ve değerleri

gibi koşullarla birlikte currenciesByCentralBank ile birleştirebilirim
currenciesByCommercialBank.CurrencyName == currenciesByCentralBank.CurrencyName 

cevap

5

Bu, en uygun şekilde olmalıdır. İlk önce para birimlerinden ticari bankalarına bir harita çizersiniz. Ardından, merkezinizden ticari bir merkeze (ilk haritaya bakıldığında) bir harita çizerek koşarsınız.

List<CurrencyItem> currenciesByCommercialBank = new ArrayList<>(); 
    List<CurrencyItem> currenciesByCentralBank = new ArrayList<>(); 
    // Build my lookup from CurrencyName to CommercialBank. 
    Map<CurrencyName, CurrencyItem> commercials = currenciesByCommercialBank 
      .stream() 
      .collect(
        Collectors.toMap(
          // Map from currency name. 
          ci -> ci.getName(), 
          // To the commercial bank itself. 
          ci -> ci)); 
    Map<CurrencyItem, CurrencyItem> commercialToCentral = currenciesByCentralBank 
      .stream() 
      .collect(
        Collectors.toMap(
          // Map from the equivalent commercial 
          ci -> commercials.get(ci.getName()), 
          // To this central. 
          ci -> ci 
        )); 
2

Aşağıdaki kod O (n), ama küçük koleksiyonları için sorun olmaz (sizin listeleri muhtemelen olan):

return currenciesByCommercialBank 
    .stream() 
    .map(c -> 
     new AbstractMap.SimpleImmutableEntry<>(
      c, currenciesByCentralBank.stream() 
             .filter(c2 -> c.currencyName == c2.currencyName) 
             .findFirst() 
             .get())) 
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); 
    } 

Yukarıdaki iddia istiyorsanız uygundur Bu currenciesByCentralBank, currenciesByCommercialBank içerisindeki her öğe için bir eşleşme içerir. İki liste uyumsuzluklar olabilir, o zaman şu uygun olacaktır:

currenciesByCommercialBank 
    .stream() 
    .flatMap(c -> 
     currenciesByCentralBank.stream() 
           .filter(c2 -> c.currencyName == c2.currencyName) 
           .map(c2 -> new AbstractMap.SimpleImmutableEntry<>(c, c2))) 
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); 

Bu durumda harita tüm eşleşmeleri içerecektir ve eksik kayıtlar şikayet olmaz.