Java:如何将BigDecimal值相加到存储在MAP内的集合中

huangapple go评论65阅读模式
英文:

Java: How to addUp BigDecimal values to Collection stored inside the MAP

问题

public class Main {

    static BigDecimal countFine(Borrowing borrowing) {

        if (borrowing == null) {
            throw new IllegalArgumentException("Borrowing collections is null");
        }
        LocalDate todaysDate = LocalDate.now();
        BigDecimal sum = BigDecimal.ZERO;
        long howManyDaysBookIsBorrowedAlready = -ChronoUnit.DAYS.between(todaysDate, borrowing.borrowingDate());
        BigDecimal amountOfDaysMinus14 = BigDecimal.valueOf(howManyDaysBookIsBorrowedAlready).subtract(BigDecimal.valueOf(14));
        if (howManyDaysBookIsBorrowedAlready <= 14) {
            sum = BigDecimal.ZERO;
        } else {
            sum = sum.add(BigDecimal.valueOf(5).multiply(amountOfDaysMinus14));
            if (borrowing.reader().age() < 18) {
                sum = sum.divide(BigDecimal.valueOf(2));
            }
        }
        return sum;
    }

    public static Map<Reader, BigDecimal> createMapReaderWithAMountOfFines(Set<Borrowing> borrowings) {

        if (borrowings == null) {
            throw new IllegalArgumentException("Borrowing set collections cannot be null");
        }
        Map<Reader, BigDecimal> readerWithAMountOfFines = new HashMap<>();

        borrowings.forEach(borrowing -> {
            if (readerWithAMountOfFines.containsKey(borrowing.reader())) {
                readerWithAMountOfFines.get(borrowing.reader()).add(countFine(borrowing));
            } else {
                readerWithAMountOfFines.put(borrowing.reader(), countFine(borrowing));
            }
        });
        return readerWithAMountOfFines;
    }

    public static void main(String[] args) {
        Reader r1 = new Reader("Tomasz", "Knapik", 21, BigDecimal.ZERO);
        Reader r2 = new Reader("Adrian", "Knapik", 16, BigDecimal.ZERO);
        Reader r3 = new Reader("Tomasz", "Kamel", 29, BigDecimal.ZERO);
        Reader r4 = new Reader("Ala", "Drag", 18, BigDecimal.ZERO);
        Reader r5 = new Reader("Ola", "Was", 28, BigDecimal.ZERO);
        Reader r6 = new Reader("Ola", "Chrzaszcz", 35, BigDecimal.ZERO);
        HashSet<Reader> readers = new HashSet<>();
        Collections.addAll(readers, r1, r2, r3, r4, r5, r6);

        Book b1 = new Book("Przedwiosnie", "Zeromski", new BigDecimal("5"));
        Book b2 = new Book("Pan Tadeusz", "Mickiewicz", new BigDecimal("8"));
        Book b3 = new Book("Kordian", "Mickiewicz", new BigDecimal("5"));
        Book b4 = new Book("Potop", "Sienkiewicz", new BigDecimal("10"));
        Book b5 = new Book("Lalka", "Prus", new BigDecimal("5"));
        HashSet<Book> books = new HashSet<>();
        Collections.addAll(books, b1, b2, b3, b4, b5);

        Borrowing w1 = new Borrowing(b1, r4, LocalDate.of(2020, 7, 1));
        Borrowing w2 = new Borrowing(b1, r1, LocalDate.of(2020, 8, 1));
        Borrowing w3 = new Borrowing(b2, r2, LocalDate.of(2020, 7, 20));
        Borrowing w4 = new Borrowing(b5, r2, LocalDate.of(2020, 7, 1));
        Borrowing w5 = new Borrowing(b5, r3, LocalDate.of(2020, 8, 1));
        Borrowing w6 = new Borrowing(b4, r2, LocalDate.of(2020, 7, 20));
        Borrowing w7 = new Borrowing(b4, r4, LocalDate.of(2020, 6, 1));
        Borrowing w8 = new Borrowing(b3, r5, LocalDate.of(2020, 7, 18));
        HashSet<Borrowing> wypozyczenia = new HashSet<>();
        Collections.addAll(wypozyczenia, w1, w2, w3, w4, w5, w6, w7, w8);

        Map<Reader, BigDecimal> readerWithAMountOfFines = createMapReaderWithAMountOfFines(wypozyczenia);
        readerWithAMountOfFines.forEach((k, v) -> System.out.println(k + " " + v));
    }
}

Note: I've translated the Java code into Chinese and provided it as requested.

英文:

Task is to practise collection and do not use streams.
There is something like library basic functionality: we have reader, book and info about borrowing.
There are 4 classes/records with following :

public record Book(String title, String author, BigDecimal priceForKeepingLonger) {} 
public record Reader(String name, String lastName, int age, BigDecimal fineAmount) {}
public record Borrowing(Book book, Reader reader, LocalDate borrowingDate) {}
psvm

Task:

  • create a map with key: Reader and as value: amount of Fine for keeping books to long (more than 14 days).
  • One user can book more than 1 book.

Question:

  • I have to add amount of fines per user and i am not able to do it. I have the method that can count it per book separately..

Could you please help.
Main class below (i am rather fresher here so hope that amount of data/code is enough):

public class Main {
static BigDecimal countFine(Borrowing borrowing){
if(borrowing == null){
throw new IllegalArgumentException(&quot;Borrowing collections is null&quot;);
}
LocalDate todaysDate = LocalDate.now();
BigDecimal sum = BigDecimal.ZERO;
long howManyDaysBookIsBorrowedAlready = -ChronoUnit.DAYS.between(todaysDate, borrowing.borrowingDate());
BigDecimal amountOfDaysMinus14 = BigDecimal.valueOf(howManyDaysBookIsBorrowedAlready).subtract(BigDecimal.valueOf(14));
if (howManyDaysBookIsBorrowedAlready &lt;=14){
sum = BigDecimal.ZERO;
}
else{
sum = sum.add(BigDecimal.valueOf(5).multiply(amountOfDaysMinus14));
if(borrowing.reader().age() &lt;18){
sum = sum.divide(BigDecimal.valueOf(2));
}
}
return sum;
}
public static Map&lt;Reader, BigDecimal&gt; createMapReaderWithAMountOfFines(Set&lt;Borrowing&gt; borrowings){
if(borrowings == null){
throw new IllegalArgumentException(&quot;Borrowing set collections cannot be null&quot;);
}
Map&lt;Reader, BigDecimal&gt; readerWithAMountOfFines = new HashMap&lt;&gt;();
borrowings.forEach(borrowing -&gt; {
if(readerWithAMountOfFines.containsKey(borrowing.reader())){
readerWithAMountOfFines.get(borrowing.reader()).add(countFine(borrowing));
}
else {
readerWithAMountOfFines.put(borrowing.reader(),countFine(borrowing));
}
} );
return readerWithAMountOfFines;
}
public static void main(String[] args) {
Reader r1 = new Reader(&quot;Tomasz&quot;, &quot;Knapik&quot;, 21, BigDecimal.ZERO);
Reader r2 = new Reader(&quot;Adrian&quot;, &quot;Knapik&quot;, 16, BigDecimal.ZERO);
Reader r3 = new Reader(&quot;Tomasz&quot;, &quot;Kamel&quot;, 29, BigDecimal.ZERO);
Reader r4 = new Reader(&quot;Ala&quot;, &quot;Drag&quot;, 18, BigDecimal.ZERO);
Reader r5 = new Reader(&quot;Ola&quot;, &quot;Was&quot;, 28, BigDecimal.ZERO);
Reader r6 = new Reader(&quot;Ola&quot;, &quot;Chrzaszcz&quot;, 35, BigDecimal.ZERO);
HashSet&lt;Reader&gt; readers = new HashSet&lt;&gt;();
Collections.addAll(readers,r1,r2,r3,r4,r5,r6);
Book b1 = new Book(&quot;Przedwiosnie&quot;, &quot;Zeromski&quot;,new BigDecimal(&quot;5&quot;));
Book b2 = new Book(&quot;Pan Tadeusz&quot;, &quot;Mickiewicz&quot;,new BigDecimal(&quot;8&quot;));
Book b3 = new Book(&quot;Kordian&quot;, &quot;Mickiewicz&quot;,new BigDecimal(&quot;5&quot;));
Book b4 = new Book(&quot;Potop&quot;, &quot;Sienkiewicz&quot;,new BigDecimal(&quot;10&quot;));
Book b5 = new Book(&quot;Lalka&quot;, &quot;Prus&quot;,new BigDecimal(&quot;5&quot;));
HashSet&lt;Book&gt; books = new HashSet&lt;&gt;();
Collections.addAll(books,b1,b2,b3,b4,b5);
Borrowing w1 = new Borrowing(b1,r4, LocalDate.of(2020,7,1));
Borrowing w2 = new Borrowing(b1,r1, LocalDate.of(2020,8,1));
Borrowing w3 = new Borrowing(b2,r2, LocalDate.of(2020,7,20));
Borrowing w4 = new Borrowing(b5,r2, LocalDate.of(2020,7,1));
Borrowing w5 = new Borrowing(b5,r3, LocalDate.of(2020,8,1));
Borrowing w6 = new Borrowing(b4,r2, LocalDate.of(2020,7,20));
Borrowing w7 = new Borrowing(b4,r4, LocalDate.of(2020,6,1));
Borrowing w8 = new Borrowing(b3,r5, LocalDate.of(2020,7,18));
HashSet&lt;Borrowing&gt; wypozyczenia = new HashSet&lt;&gt;();
Collections.addAll(wypozyczenia,w1,w2,w3,w4,w5,w6,w7,w8);
Map&lt;Reader, BigDecimal&gt; readerWithAMountOfFines = createMapReaderWithAMountOfFines(wypozyczenia);
readerWithAMountOfFines.forEach((k,v) -&gt; System.out.println(k + &quot; &quot; + v));
}

答案1

得分: 2

在计算读者的罚款总额时,请记住 BigDecimal.add 方法会返回总和,而不会修改现有值。

因此,要将新的罚款金额添加到现有罚款中,您需要获取现有罚款,将新罚款相加,并将结果存储回 readerWithAMountOfFines

BigDecimal existingFineAmount = readerWithAMountOfFines.get(borrowing.reader());
BigDecimal newFineAmount = existingFineAmount.add(countFine(borrowing));
readerWithAMountOfFines.put(borrowing.reader(), newFineAmount);
英文:

Where you are adding up the fines for the reader, you need to remember that the BigDecimal.add method returns the sum, it does not not modify the existing value.

So to add the new fine to the existing fine you need to retrieve the existing fine, add the new fine, and store the result back in readerWithAMountOfFines:

BigDecimal existingFineAmount = readerWithAMountOfFines.get(borrowing.reader());
BigDecimal newFineAmount = existingFineAmount.add(countFine(borrowing));
readerWithAMountOfFines.put(borrowing.reader(), newFineAmount);
</details>
# 答案2
**得分**: 0
Here's the translated code:
```java
我在这里找到了另一种解决方案,使用了合并(merge)方法:
public static Map<Reader, BigDecimal> createMapReaderWithAMountOfFines(Set<Borrowing> borrowings){
if(borrowings == null){
throw new IllegalArgumentException("借阅集合不能为空");
}
Map<Reader, BigDecimal> readerWithAMountOfFines = new HashMap<>();
borrowings.forEach(borrowing -> {
if(readerWithAMountOfFines.containsKey(borrowing.reader())){
readerWithAMountOfFines.merge(borrowing.reader(), countFine(borrowing), BigDecimal::add);
}
else {
readerWithAMountOfFines.put(borrowing.reader(), countFine(borrowing));
}
} );
return readerWithAMountOfFines;
}
英文:

I found another solution here using merge method

public static Map&lt;Reader, BigDecimal&gt; createMapReaderWithAMountOfFines(Set&lt;Borrowing&gt; borrowings){
if(borrowings == null){
throw new IllegalArgumentException(&quot;Borrowing set collections cannot be null&quot;);
}
Map&lt;Reader, BigDecimal&gt; readerWithAMountOfFines = new HashMap&lt;&gt;();
borrowings.forEach(borrowing -&gt; {
if(readerWithAMountOfFines.containsKey(borrowing.reader())){
readerWithAMountOfFines.merge(borrowing.reader(),countFine(borrowing),BigDecimal::add);
}
else {
readerWithAMountOfFines.put(borrowing.reader(),countFine(borrowing));
}
} );
return readerWithAMountOfFines;
}

huangapple
  • 本文由 发表于 2020年8月14日 21:03:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/63413309.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定