简体   繁体   中英

How to get special part of string using java streams?

I have file abbreviations.txt where I have special infos:

Example abbreviations.txt :

PCAP_Personal Computer_Apple
NBHP_NoteBook_Hewlett Packard
TVSG_Televisor_Samsung

and I need to get all brand names into new List String. Im trying use this:

 Stream<String> abbreviations = Files.lines(Paths.get("src/main/resources/raceData/abbreviations.txt"))
            .flatMap(Pattern.compile("_")::splitAsStream);
    List<String> dates = abbreviations.collect(Collectors.toList());
    dates.forEach(System.out::println);

But as List I get:

PCAP_Personal Computer
Apple
TVSG_Televisor
Samsung
NBHP_NoteBook
Hewlett Packard

splitAsStream ?

That's not necessary. Just use

.map(line -> line.split("_")[2])

This of course assumes that all lines have the correct format. You could of course filter out malformed lines, for example, using

.map(line -> line.split("_"))
.filter(parts -> parts.length >= 3)
.map(parts -> parts[2])

You could then put it into an array, using toArray . However, I recommend to use a List instead, because by far the most implementations are way more powerful. You can do so using a Collector :

.collect(Collectors.toList());

If the brand names are what is after the last '_'

    String s = "PCAP_Personal Computer_Apple\n" +
            "NBHP_NoteBook_Hewlett Packard\n" +
            "TVSG_Televisor_Samsung" ;

    Stream<String> abbreviations = Arrays.stream(s.split("\\n"));
    List<String> brandNames  =  abbreviations
            .map(abbr -> abbr.substring(abbr.lastIndexOf('_') + 1))
            .collect(Collectors.toList());

    brandNames.forEach(System.out::println);

will print you

Apple
Hewlett Packard
Samsung

If you need them to be an array, just use

            String[]  brandNames  =  abbreviations
                .map(abbr -> abbr.substring(abbr.lastIndexOf('_') + 1))
                .toArray(String[]::new);

Try this. It just deletes everything up to and including the last underscore.

String[] lines = { "PCAP_Personal Computer_Apple",
        "NBHP_NoteBook_Hewlett Packard",
        "TVSG_Televisor_Samsung",
        "And_more_than_two_underscores_IBM" };

List<String> vendors = Arrays.stream(lines)
        .map(str -> str.replaceAll(".*(?>_)", ""))
        .collect(Collectors.toList());
vendors.forEach(System.out::println);

Prints

Apple
Hewlett Packard
Samsung
IBM

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