简体   繁体   中英

Java Stream map or create new object of a FileStream

If I have a file which is tab separated, when I use the BufferedReader object I can use Stream Api like filter, map, reduce, etc. methods so if Stream

 //first Line is Header Identified by #
 #  SUBSTANCE   2,60    25.04.2012  00:02:48    01.01.2000  24.04.2012
 //this is my R Object which has attached two RN Objects
 R  10  -   016-053-00-8    402-460-1   0   0   0   0   0   0
 RN 10  0   DE  (C16oderC18-n-Alkyl)(C16oderC18-n-alkyl)ammonium-2-((C16oderC18-n-alkyl)(C16oderC18-n-alkyl)carbamoyl)benzolsulfonat
 RN 10  0   EN  (C16orC18-n-alkyl)(C16orC18-n-alkyl)ammonium 2-((C16orC18-n-alkyl)(C16orC18-n-alkyl)carbamoyl)benzenesulfonate

I need to create a Object or a MAP (Header, rObject (rnObject,rnObject)) like a nested Array, so can I use the Stream API to do this?

I already tried

    BufferedReader in = new BufferedReader(new FileReader(absoluteFilePath));

    List test = in.lines().limit(4).filter(identifier -> identifier.startsWith("RN")).map(line -> line.split("\\t")).collect(Collectors.toList());

So obviously it is not working since I get the output

    test.forEach(it -> System.out.println(it));
    [Ljava.lang.String;@326de728
    [Ljava.lang.String;@25618e91

So I thought I could create a Map with the Stream Api so I think the way I want it is not possible so I could just create a while lop and create so the objects what you think?

The best thing is to correctly identify the List as a List of String and do not use raw list.

As the result of the split is a string array you have to wrap it as a list.

Then you will have a list of list, for this use flatMap to merge all the list into a unique one, then you will be able to use the collector and store it in a single list.

List<String> test = in.lines().limit(4).filter(identifier -> identifier.startsWith("RN")).map(line -> Arrays.asList(line.split("\\t"))).flatMap(List::stream).collect(Collectors.toList());

The main problem with your example is that you were storing a raw list of arrays objects. So when you call toString() into an array you get that hashReference starting with a square bracket.

Hope this helps you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM