메소드참조

さようなら。冬·2020년 12월 16일
0
package examp;

import java.util.ArrayList;
import java.util.List;

public class RevolutionDto {
	List<Dto> list;

	List<Dto> getList() {
		return list;
	}

	void setList(List<Dto> list) {
		this.list = list;
	}

	public RevolutionDto() {
		list = new ArrayList<Dto>();
	}

	public void accumulated(Dto dto) {
		list.add(dto);
	}
	
	public void combine(RevolutionDto rdto) {
		list.addAll(rdto.getList());
	}
	
}

package examp;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class CollectionEx {
	public static void main(String args[]) {
		Dto[] dtoArr = new Dto[10];
		String type="";
		for(int i=0;i<10;i++) 
		{
			int a= 1111;
			if(i%2==0) 
			{
				type="type1";
				
			}else 
			{
				type="type2";
				
			}
			dtoArr[i] = new Dto(a*i,String.valueOf(a*i),type);
		}
		 System.out.println("람다");
		 List<Dto> dtoList = Arrays.asList(dtoArr);
		 RevolutionDto revolutionDto = dtoList.stream()
				                              .filter(s->s.getId()%2 == 0)
				 							  .collect(
				 									  ()->new RevolutionDto(),
				 									  (r,t)->r.accumulated(t),
				 									  (r1,r2) ->r1.combine(r2));
	     RevolutionDto revolutionDto1 = dtoList.stream().filter(s->s.getId()%2 ==0).collect(RevolutionDto::new,RevolutionDto::accumulated,RevolutionDto::combine);	 
	     System.out.println(revolutionDto);
	     System.out.println(revolutionDto1);

	 //type으로 group 하기
     
	     Map<?,List<Dto>> dtoGroupingMap =dtoList.stream().collect(Collectors.groupingBy(Dto::getId));
	     Map<?,List<Dto>> dtoGroupingMapOrderById =dtoList.stream().collect(Collectors.groupingBy(Dto::getId));
	     System.out.println("dtoGroupingMap:::::"+dtoGroupingMap.toString().toString());  
	     System.out.println("dtoGroupingMapOrderById:::::"+dtoGroupingMapOrderById.toString().toString());  
	
	     //type으로  type1,2 각각의 id의 평균치를 계산 
	     Map <String,Double> dtogroupingMapByType =  dtoList.stream().collect(Collectors.groupingBy(Dto::getType,Collectors.averagingDouble(Dto::getId)));
	     System.out.println("dtogroupingMapByType::::::::"+dtogroupingMapByType.toString().toString());
	
	     
	     //type을 키로 하고 나머지 id를 쉼표로 가져오는 방법 
	     Map<?,?> dtogroupingMapByTypeCombineSemiCol = dtoList.stream().collect(Collectors.groupingBy(Dto::getType,Collectors.mapping(Dto::getName,Collectors.joining(","))));
> 	     System.out.println("dtogroupingMapByTypeCombineSemiCol::::::::"+dtogroupingMapByTypeCombineSemiCol.toString().toString());
	}
}

0개의 댓글