목록

2017-12-22 6 views
4
public class A 
{ 
    private B[] b; 
    //getter setter 
} 

public class B 
{ 
    private String id; 
    //getter setter 
} 

이미 다음과 같이 스트림에서 객체를 가지고 있지만, B 클래스 내부 ID의 목록을 얻을이 람다를 완료하는 방법을 찾을 수 없습니다 내부에 배열 람다를 작성하는 방법.목록

Stream <String> lines = Files.lines(Paths.get("file.json")); 
lines.map(x -> (A)gson.fromJson(x, type))... 

답변

5

현재 flatMap를 찾고 있습니다 :

lines.map(x -> (A)gson.fromJson(x, type)) 
     .flatMap(y -> Arrays.stream(y.getB())) 
     .map(B::getId) 
     .collect(Collectors.toSet()) // or any other terminal operation 
2

당신은 flatMap 사용할 필요가 :

lines.map(x -> (A)gson.fromJson(x, type)).flatMap(a -> Arrays.stream(a.getB()) 

을 지금은 Stream<B>이다; 당신은 지금

.map(B::getId) 

자신의 ID에 해당 매핑이 밖으로 목록을 만들 수 있습니다.

.collect(Collectors.toList()); 
+0

영업을 원한다 B의 ID와 목록 '목록 입찰 lines.map (X -> (A) gson.fromJson (X, 유형)). flatMap (a -> Arrays.stream (a.getB()). map (B :: getId). 콜렉터 (Collectors.toList()), ' –

+0

@ DavidPrezCabrera 네가 맞다. – daniu