Merge pull request #15962 from sk1418/modify-print-list

[modify-print-list] modify + print a list
This commit is contained in:
Liam Williams 2024-03-02 13:44:45 +00:00 committed by GitHub
commit c35329d003
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 55 additions and 1 deletions

View File

@ -29,4 +29,4 @@
<properties>
<vavr.version>0.10.4</vavr.version>
</properties>
</project>
</project>

View File

@ -0,0 +1,54 @@
package com.baeldung.modifyandprint;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Lists;
public class ModifyAndPrintListElementsUnitTest {
private final Logger log = LoggerFactory.getLogger(ModifyAndPrintListElementsUnitTest.class);
@Test
void whenPrintingInForEach_thenListIsPrinted() {
List<String> theList = Lists.newArrayList("Kai", "Liam", "Eric", "Kevin");
theList.forEach(element -> log.info(element));
}
@Test
void whenUsingModifyAndPrintingSeparately_thenListIsModifiedAndPrinted() {
List<String> theList = Lists.newArrayList("Kai", "Liam", "Eric", "Kevin");
theList.replaceAll(element -> element.toUpperCase());
theList.forEach(element -> log.info(element));
assertEquals(List.of("KAI", "LIAM", "ERIC", "KEVIN"), theList);
}
@Test
void whenPrintingInMap_thenStreamIsModifiedAndPrinted() {
List<String> theList = List.of("Kai", "Liam", "Eric", "Kevin");
List<String> newList = theList.stream()
.map(element -> {
String newElement = element.toUpperCase();
log.info(newElement);
return newElement;
})
.collect(Collectors.toList());
assertEquals(List.of("KAI", "LIAM", "ERIC", "KEVIN"), newList);
}
@Test
void whenPrintingInPeek_thenStreamIsModifiedAndPrinted() {
List<String> theList = List.of("Kai", "Liam", "Eric", "Kevin");
List<String> newList = theList.stream()
.map(element -> element.toUpperCase())
.peek(element-> log.info(element))
.collect(Collectors.toList());
assertEquals(List.of("KAI", "LIAM", "ERIC", "KEVIN"), newList);
}
}