Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
399 views
in Technique[技术] by (71.8m points)

java - JAVA:使用流API或Lambda从管道分隔的字符串中过滤特定的列(JAVA: Filter particular columns from pipe separated string using stream api or lambda)

Suppose I have a string/object having some data in pipe separated format as below

(假设我有一个字符串/对象,其中某些数据采用管道分隔格式,如下所示)

***Input:***
TIMESTAMP|COUNTRYCODE|RESPONSETIME|FLAG
1544190995|US|500|Y
1723922044|GB|370|N
1711557214|US|750|Y

I want to read this string/object and filter data based on particular columns names (assume for eg. TIMESTAMP and FLAG).

(我想读取此字符串/对象并根据特定的列名过滤数据(假设为TIMESTAMP和FLAG)。)

And return/display the output as shown below-

(并返回/显示输出,如下所示-)

***Output:***
TIMESTAMP|FLAG
1544190995|Y
1723922044|N
1711557214|Y

I tired using below code -

(我用下面的代码累了-)

1. First i have required header names stored an array(headerArray[] = {TIMESTAMP, FLAG}).
2. By comparing headerArray[] with first row of input, I got the index of specified column header in input. 
(headerIndex[] = {0, 3})
3. Then tried using below code to filter and get the specified columns and values
       return br.lines()
                .skip(1) // skip headers
                .map(s -> s.split("|"))
                .filter(a -> a[0] && a[3])
                .collect(Collectors.toList());

Note: I have over a million lines of pipe separated values.

(注意:我有超过一百万行的管道分隔值。)

And i wanted to return all filtered out column values in a single object.

(我想在单个对象中返回所有过滤出的列值。)

(I suppose that not possible by returning value as list)

((我想不可能通过返回值作为列表))

  ask by Shakthi Raj translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have some problems:

(您有一些问题:)

first you should change split 's pattern to \\|

(首先,您应该将split的模式更改为\\|)

and instead of filter you can you map to create new string.

(而不是过滤器,您可以map以创建新的字符串。)

 br.lines().skip(1) // skip headers
            .map(s -> s.split("\|"))
            .map(a -> String.join("|", a[0], a[3]))
            .collect(toList())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...