자바 8 복잡 사례
11146 단어 Java
package stream;
import com.xrz.entity.Car;
import com.xrz.entity.House;
import com.xrz.entity.Worker;
import org.junit.Before;
import org.junit.Test;
import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.stream.Collectors.*;
/**
* @Author XRZ
* @Date 2020/7/31 11:17
* @Version :
* @Description :
*/
public class S {
private List list;
@Before
public void before() {
list = new ArrayList<>();
list.add(new Worker(" ", " ", Boolean.FALSE, 10000, Arrays.asList(new Car(" "), new Car(" ")), Arrays.asList(new House(" "))));
list.add(new Worker(" ", " ", Boolean.FALSE, 8000, Arrays.asList(new Car(" ")), null));
list.add(new Worker(" ", " ", Boolean.FALSE, 6000, null, null));
list.add(new Worker(" ", " ", Boolean.FALSE, 5000, Arrays.asList(new Car(" ")), Arrays.asList(new House(" "))));
list.add(new Worker(" ", " ", Boolean.TRUE, 10000, null, Arrays.asList(new House(" "))));
list.add(new Worker(" ", " ", Boolean.TRUE, 13000, Arrays.asList(new Car(" ")), Arrays.asList(new House(" "), new House(" "))));
}
@Test // flatMap :
public void test01() {
//
list.stream()
.map(Worker::getCarList)
.filter(Objects::nonNull)
// Stream> -> Stream
.flatMap(Collection::stream)
.map(Car::getBrand)
.collect(toList())
.forEach(brand -> {
System.out.println(brand);
});
}
@Test // allMatch、anyMatch、noneMatch
public void test02() {
// 2500 true
boolean allMatch = list.stream().allMatch(v -> v.getSalary() > 2500);
// 10000 true
boolean anyMatch = list.stream().anyMatch(v -> v.getSalary() > 10000);
// 2500 false
boolean noneMatch = list.stream().noneMatch(v -> v.getSalary() > 2500);
}
@Test // findFirst、findAny
public void test03() {
Predicate isMan = (v) -> v.getSex().equals(" ");
//
Optional findFifst = list.parallelStream().filter(isMan).findFirst();
// ||
Optional findAny = list.parallelStream().filter(isMan).findAny();
}
@Test // sorted
public void test04() {
// ASE
list.stream()
// reversed DESC
.sorted(Comparator.comparing(Worker::getSalary)/*.reversed()*/)
.forEach(System.out::println);
// ,
Comparator byName = Comparator.comparing(Worker::getSalary);
Comparator bySex = Comparator.comparing(Worker::getSex);
Comparator comparator = bySex.thenComparing(byName);
list.stream()
.sorted(comparator)
.forEach(System.out::println);
}
//===================================================[Collectors]==================================================================
@Test // Collectors.toList()
public void test05() {
//
List list1 = list.stream().map(Worker::getName)
.collect(
//
() -> new ArrayList(),
// ,
(z, t) -> z.add(t),
//
(r, z) -> r.addAll(z)
);
List list2 = list.stream().map(Worker::getName)
.collect(
ArrayList::new,
ArrayList::add,
ArrayList::addAll
);
List list3 = list.stream().map(Worker::getName)
.collect(
LinkedList::new,
LinkedList::add,
LinkedList::addAll
);
List list4 = list.stream().map(Worker::getName).collect(toList());
List list5 = list.stream().map(Worker::getName).collect(toCollection(LinkedList::new));
}
@Test // 、
public void test06() {
// Collectors.counting()
// Long workerCount = list.stream().count();
Long workerCount = list.stream().collect(Collectors.counting());
// Collectors.maxBy()
// Optional maxBy = list.stream().max(Comparator.comparing(Worker::getSalary));
Optional maxBy = list.stream().collect(Collectors.maxBy(Comparator.comparing(Worker::getSalary)));
// Collectors.minBy()
// Optional minBy = list.stream().min(Comparator.comparing(Worker::getSalary));
Optional minBy = list.stream().collect(Collectors.minBy(Comparator.comparing(Worker::getSalary)));
// Collectors.averagingInt()
// Double average = list.stream().mapToInt(Worker::getSalary).average().getAsDouble();
Double average = list.stream().collect(Collectors.averagingInt(Worker::getSalary));
// Collectors.summing()
// Integer sum = list.stream().mapToInt(Worker::getSalary).sum();
Integer sum = list.stream().collect(Collectors.summingInt(Worker::getSalary));
// Collectors.summarizingInt()
IntSummaryStatistics collect = list.stream().collect(Collectors.summarizingInt(Worker::getSalary));
collect.getMax();
collect.getMin();
collect.getAverage();
collect.getCount();
collect.getSum();
}
@Test // Collectors.joining
public void test07() {
// Collectors.joining(" "," "," ")
String join = list.stream().map(Worker::getName).collect(joining());
//
list.stream().collect(reducing("", Worker::getName, (n1, n2) -> n1 + n2));
list.stream().map(Worker::getName).collect(reducing("", Function.identity(), (n1, n2) -> n1 + n2));
//
String join1 = list.stream().map(Worker::getName)
.collect(
() -> new StringBuilder(),
(builder, name) -> builder.append(name),
(res, builder) -> res.append(builder)
).toString();
String join2 = list.stream().map(Worker::getName)
.collect(
StringBuilder::new,
StringBuilder::append,
StringBuilder::append
).toString();
System.out.println(join); //
System.out.println(join1); //
System.out.println(join2); //
}
@Test // Collectors.groupingBy()
public void test08() {
//
Map> map1 = list.stream().collect(groupingBy(Worker::getSex));
//
Map> map2 = list.stream().collect(groupingBy(Worker::getSex, mapping(Worker::getName, toList())));
//
Map map3 = list.stream().collect(groupingBy(Worker::getSex, counting()));
//
Map map4 = list.stream().collect(groupingBy(Worker::getSex, averagingInt(Worker::getSalary)));
//
/*
{
" ":{
"true": [{"name": " "}],
"false": [{"name": " "}]
},
" ":{
"true": [{"name": " "}],
"false": [{"name": " "}]
}
}
*/
Map>> map5 = list.stream()
.collect(groupingBy(Worker::getSex, groupingBy(Worker::getMarried)));
/*
{
" ":{"name":" "},
" ":{"name":" "}
}
*/
Map map6 = list.stream()
.collect(groupingBy(
Worker::getSex,
// collect
collectingAndThen(
// collect
maxBy(Comparator.comparing(Worker::getSalary)),
//
Optional::get
))
);
/*
,
{
" ":{
" ":" ",
" ":" 、 ",
" ":""
},
" ":{
" ":" ",
" ":" ",
" ":"",
}
}
*/
Map> map7 = list.stream()
.collect(groupingBy(Worker::getSex,
groupingBy(Worker::getName,
collectingAndThen(
mapping(Worker::getCarList, toList()),
v -> v.stream()
.filter(Objects::nonNull)
.flatMap(Collection::stream)
.map(Car::getBrand)
.collect(joining("、"))
)
)
));
}
@Test // Collectors.partitioningBy()
public void test09(){
//
Map> par1 = list.stream().collect(partitioningBy(Worker::getMarried));
// 1w {false=[ , , , , ], true=[ ]}
Map> par2 = list.stream()
.collect(partitioningBy(
worker -> worker.getSalary() > 10000,
mapping(Worker::getName, toList())
)
);
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JPA + QueryDSL 계층형 댓글, 대댓글 구현(2)이번엔 전편에 이어서 계층형 댓글, 대댓글을 다시 리팩토링해볼 예정이다. 이전 게시글에서는 계층형 댓글, 대댓글을 구현은 되었지만 N+1 문제가 있었다. 이번에는 그 N+1 문제를 해결해 볼 것이다. 위의 로직은 이...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.