Anonymous H
Anonymous H

Reputation: 1

How to check the contents of Stream object without converting into array in Java 8?

Basically I have to do the following: 1)Read the CSV input file. 2)Filter the CSV data based on the blacklist. 3)Sort the input based on the country names in ascending order. 4)Print the records which are not blacklisted. The CSV file contains: id,country-short,country 1,AU,Australia 2,CN,China 3,AU,Australia 4,CN,China The blacklist file contains: AU JP And the desired output is 2,CN,China 4,CN,China

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamProcessing {
    public static void filterCsv(String fileName, String blacklistFile){


         try (Stream<String> stream1 = Files.lines(Paths.get(fileName))) {
             Stream<String> stream2 = Files.lines(Paths.get(blacklistFile));
             Optional<String> hasBlackList = stream1.filter(s->s.contains(stream2)).findFirst();
         } catch (IOException e) {
             e.printStackTrace();
         }
    }   



    public static void main(String args[])
    {
        StreamProcessing sp = new StreamProcessing();
        sp.filterCsv("Data.csv","blacklist.txt");
    }
}

I want to remove the entries that are present in second Stream from comparing from the first Stream without converting it into an array?

Upvotes: 0

Views: 129

Answers (2)

sprinter
sprinter

Reputation: 27966

Unfortunately you can't use a stream more than once so code that checks the blacklist stream for each line will fail. The easiest solution would be to store the blacklist in a collection and then check each line against it.

List<String> blacklist = Files.readAllLines(Paths.get(blacklistFile));
boolean hasBlacklist = Files.lines(Paths.get(filename)).anyMatch(blacklist::contains);

Upvotes: 1

Marko Topolnik
Marko Topolnik

Reputation: 200168

You can consume a stream only once. Since you need access to all the members of the blacklist while evaluating each member of the main file, you must first consume the blacklist stream in entirety. For efficiency reasons, don't convert to an array, but to a HashSet.

boolean hasBlacklistedWord(String fileName, String blacklistFile) {
    Set<String> blacklist = Files.lines(Paths.get(blacklistFile)).collect(toSet());
    return Files.lines(Paths.get(fileName)).anyMatch(s -> blacklist.contains(s));
}

Upvotes: 3

Related Questions