java8 lamda 표현식은 List를 그룹으로 나누고, List는 조건에 따라 필터합니다

24318 단어 java 기초
예제 객체:
    private Integer id;
    private String name;
    private BigDecimal money;
    private Integer num;
    public Apple(Integer id, String name, BigDecimal money, Integer num) {
        this.id = id;
        this.name = name;
        this.money = money;
        this.num = num;
    }
}

테스트 데이터

List<Apple> appleList = new ArrayList<>();// apple 
 
Apple apple1 =  new Apple(1," 1",new BigDecimal("3.25"),10);
Apple apple12 = new Apple(1," 2",new BigDecimal("1.35"),20);
Apple apple2 =  new Apple(2," ",new BigDecimal("2.89"),30);
Apple apple3 =  new Apple(3," ",new BigDecimal("9.99"),40);
 
appleList.add(apple1);
appleList.add(apple12);
appleList.add(apple2);
appleList.add(apple3);


1. 그룹
List 안의 대상 요소는 어떤 속성으로 그룹을 나눈다. 예를 들어 id로 그룹을 나누고 id를 똑같이 놓는다.
//List  ID  Map>
Map<Integer, List<Apple>> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId));
 
System.err.println("groupBy:"+groupBy);
{1=[Apple{id=1, name=' 1', money=3.25, num=10}, Apple{id=1, name=' 2', money=1.35, num=20}], 2=[Apple{id=2, name=' ', money=2.89, num=30}], 3=[Apple{id=3, name=' ', money=9.99, num=40}]}

2, 리스트 전환 맵
id는 키이고 apple 객체는value입니다.
/**
 * List -> Map
 *  :
 * toMap  key, Duplicate key ....  。。。
 *  apple1,apple12 id 1。
 *    (k1,k2)->k1  , key, key1, key2
 */
Map<Integer, Apple> appleMap = appleList.stream().collect(Collectors.toMap(Apple::getId, a -> a,(k1,k2)->k1));
 
{1=Apple{id=1, name=' 1', money=3.25, num=10}, 2=Apple{id=2, name=' ', money=2.89, num=30}, 3=Apple{id=3, name=' ', money=9.99, num=40}}

3. 필터 필터
컬렉션에서 기준에 맞는 요소를 필터링합니다.
// 
List<Apple> filterList = appleList.stream().filter(a -> a.getName().equals(" ")).collect(Collectors.toList());
 
System.err.println("filterList:"+filterList);
[Apple{id=2, name=' ', money=2.89, num=30}]

4. 화해를 구한다
컬렉션의 데이터를 속성별로 합치려면 다음과 같이 하십시오.
//   
BigDecimal totalMoney = appleList.stream().map(Apple::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
System.err.println("totalMoney:"+totalMoney);  //totalMoney:17.48

5. 흐름 중 최대 최소값 찾기
Collectors.maxBy 및 Collectors.minBy는 흐름의 최대 또는 최소 값을 계산합니다.
Optional<Dish> maxDish = Dish.menu.stream().
      collect(Collectors.maxBy(Comparator.comparing(Dish::getCalories)));
maxDish.ifPresent(System.out::println);
 
Optional<Dish> minDish = Dish.menu.stream().
      collect(Collectors.minBy(Comparator.comparing(Dish::getCalories)));
minDish.ifPresent(System.out::println);

6.제중
import static java.util.Comparator.comparingLong;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;
 
//  id 
     List<Person> unique = appleList.stream().collect(
                collectingAndThen(
                        toCollection(() -> new TreeSet<>(comparingLong(Apple::getId))), ArrayList::new)
        );

Collectors 클래스의 정적 플랜트 방법:
공장 방법
반환 유형
역할
toList
List
흐름의 모든 항목을 하나의 List로 수집
toSet
Set
흐름 중의 모든 항목을 하나의 Set에 수집하여 중복 항목을 삭제합니다
toCollection
Collection
흐르는 모든 항목을 공급원에서 만든 집합menuStream에 수집합니다.collect(toCollection(), ArrayList::new
counting
Long
흐름 중의 원소의 개수를 계산하다
sumInt
Integer
흐름 항목의 정수 속성 구화
averagingInt
Double
흐름 항목 Integer 속성의 평균 값 계산하기
summarizingInt
IntSummaryStatistics
스트림 항목 Integer 속성에 대한 통계값(예: 최대, 최소, 합계, 평균)을 수집합니다.
joining
String
흐르는 항목마다 toString 방법을 호출하여 생성된 문자열collect 연결하기 (joining (",")
maxBy
Optional
흐름에서 주어진 비교기에 따라 선택한 최대 요소를 감싸거나, 흐름이 비어 있으면 Optional입니다.empty()
minBy
Optional
흐름에서 주어진 비교기에 따라 선택한 최소 요소를 감싸거나, 흐름이 비어 있으면 Optional입니다.empty()
reducing
귀속 조작이 발생하는 유형
누적기로서의 초기 값부터 Binary Operator를 이용하여 흐름 속의 원소와 하나하나 결합시켜 흐름을 단일 값으로 합쳐 int total Calories = menuStream을 누적한다.collect(reducing(0, Dish::getCalories, Integer::sum));
collectingAndThen
변환 함수 반환 유형
다른 컬렉터를 감싸고 그 결과에 변환 함수 int howMany Dishes = menuStream을 적용합니다.collect(collectingAndThen(toList(), List::size))
groupingBy
Map
항목의 속성 값에 따라 흐름에 있는 항목에 대한 질문 그룹을 만들고 속성 값을 결과 맵의 키로 사용합니다
partitioningBy
Map
흐르는 항목마다 술어를 응용한 결과에 따라 항목을 구분하다
본 논문은 csdn 문장에서 전재되었습니다:java8 lamda 표현식은 빠른 List 회전 맵을 실현하고,List는 그룹을 나누며,List는 조건에 따라 필터합니다

좋은 웹페이지 즐겨찾기