001/** 002 * Copyright (c) 2012, 2014, Credit Suisse (Anatole Tresch), Werner Keil and others by the @author tag. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not 005 * use this file except in compliance with the License. You may obtain a copy of 006 * the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 012 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 013 * License for the specific language governing permissions and limitations under 014 * the License. 015 */ 016package org.javamoney.moneta.function; 017 018import java.util.Map; 019import java.util.Objects; 020 021import javax.money.CurrencyUnit; 022import javax.money.MonetaryAmount; 023 024/** 025 * Internal class implementing grouped statistic functionality. 026 */ 027public class GroupMonetarySummaryStatistics { 028 029 private Map<CurrencyUnit, MonetarySummaryStatistics> groupSummary = new MonetarySummaryMap(); 030 031 GroupMonetarySummaryStatistics() { 032 033 } 034 035 public Map<CurrencyUnit, MonetarySummaryStatistics> get() { 036 return groupSummary; 037 } 038 039 public GroupMonetarySummaryStatistics accept(MonetaryAmount amount) { 040 CurrencyUnit currency = Objects.requireNonNull(amount).getCurrency(); 041 groupSummary.putIfAbsent(currency, new DefaultMonetarySummaryStatistics( 042 currency)); 043 MonetarySummaryStatistics summary = groupSummary.get(currency); 044 summary.accept(amount); 045 return this; 046 } 047 048 @Override 049 public int hashCode() { 050 return Objects.hash(groupSummary); 051 } 052 053 @Override 054 public boolean equals(Object obj) { 055 if (GroupMonetarySummaryStatistics.class.isInstance(obj)) { 056 GroupMonetarySummaryStatistics other = GroupMonetarySummaryStatistics.class 057 .cast(obj); 058 return Objects.equals(groupSummary, other.groupSummary); 059 } 060 return false; 061 } 062 063 @Override 064 public String toString() { 065 return "GroupMonetarySummaryStatistics: " + groupSummary.toString(); 066 } 067 068 public GroupMonetarySummaryStatistics combine( 069 GroupMonetarySummaryStatistics another) { 070 Objects.requireNonNull(another); 071 072 for (CurrencyUnit keyCurrency : another.groupSummary.keySet()) { 073 groupSummary.putIfAbsent(keyCurrency, 074 new DefaultMonetarySummaryStatistics(keyCurrency)); 075 groupSummary.merge(keyCurrency, 076 another.groupSummary.get(keyCurrency), 077 MonetarySummaryStatistics::combine); 078 } 079 return this; 080 } 081 082}