2017-05-22 1 views
3

어떻게 이 monitoredData 클래스는이 3 개 개인 변수가, 스트림을 사용하여 ArrayList <MonitoredData>에 내가 텍스트 파일에서 읽을 수있는 모든 요소를 ​​넣을 수 있습니다 : private Date startingTime, Date finishTime, String activityLabel을;분할 스트림 및 텍스트 파일에서 목록에 넣어

텍스트 파일 Activities.txt는 다음과 같습니다

첫 번째 두 문자열이 다음 하나 개의 빈 공간, 2 개 탭, 하나의 공백으로 구분

다시 등등

2011-11-28 02:27:59  2011-11-28 10:18:11  Sleeping   
2011-11-28 10:21:24  2011-11-28 10:23:36  Toileting 
2011-11-28 10:25:44  2011-11-28 10:33:00  Showering 
2011-11-28 10:34:23  2011-11-28 10:43:00  Breakfast 

와 .... , 2 개의 탭.

String fileName = "D:/Tema 5/Activities.txt"; 

    try (Stream<String> stream = Files.lines(Paths.get(fileName))) { 

     list = (ArrayList<String>) stream 
       .map(w -> w.split("\t\t")).flatMap(Arrays::stream) // \\s+ 
       .collect(Collectors.toList()); 

     //list.forEach(System.out::println); 

    } catch (IOException e) { 

     e.printStackTrace(); 
    } 
+5

'w.split()'은 3 개의 문자열 배열을 생성합니다. 이제 그 배열을'MonitoredData'에'맵핑 '해야합니다. 'MonitoredData'에게 배열을 취하는 생성자를 주거나 생성자를 호출하는 람다를 가져라 – Arkadiy

+0

'Collectors.toList()'의 결과를'ArrayList'로 형 변환하지 마십시오. 선언 된 타입이'ArrayList' 대신에'List' 인 이유가 있습니다. 결과가'ArrayList'라는 보장은 없습니다. – Holger

+0

도움을 주셔서 감사합니다. @Arkadiy! – Nico

답변

3

당신이 예에서 내가 만들 Function을 사용하고는 MonitoredData을 만들기 위해 공장을 소개 필요 MonitoredDataString[]에서 : 코드는 스트림에서 작동

Function<String[],MonitoredData> factory = data->{ 
    DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
    try{ 
    return new MonitoredData(format.parse(data[0]),format.parse(data[1]),data[2]); 
    //      ^--startingTime  ^--finishingTime  ^--label 
    }catch(ParseException ex){ 
    throw new IllegalArgumentException(ex); 
    } 
}; 

것은 THEN해야한다 아래와 같이 결과를 캐스팅 할 필요가 없습니다. Collectors#toCollection :

list = stream.map(line -> line.split("\t\t")).map(factory::apply) 
      .collect(Collectors.toCollection(ArrayList::new)); 
관련 문제