Beforeu
Beforeu

Reputation: 83

Is there anyway to set value that depends on result of the stream inside stream chain

I need to write a stream chain that will return specified console output.

I managed to get proper result but i had to break my stream chain and im wondering if there is any way to avoid it

public class Main {
    public static void main(String[] args) throws IOException {
        Map<String, List<String>> map;
        int maxValue;
        map = new BufferedReader(
                new InputStreamReader(
                        new URL("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")
                                .openStream(), StandardCharsets.UTF_8))
                .lines().flatMap(Pattern.compile("[\\r\\n]")::splitAsStream)
                .collect(Collectors.groupingBy(s -> Stream.of(s.split(""))
                        .sorted().collect(Collectors.joining()), Collectors.toList()));

        maxValue = map.values().stream().mapToInt(List::size).max().getAsInt();

        map.values().stream().filter(l -> l.size() == maxValue).collect(Collectors.toList())
                .stream().sorted(Comparator.comparing(s -> s.get(0))).collect(Collectors.toList()).
                forEach(n -> System.out.println(n.stream().sorted().collect(Collectors.joining(" "))));
    }
}

I would like to get the same result as in my code but instead of setting maxValue outside the stream chain it should be set inside.

Upvotes: 1

Views: 59

Answers (1)

Samuel Philipp
Samuel Philipp

Reputation: 11040

You can use a TreeMap and its last entry to collect all the max values:

new BufferedReader(new InputStreamReader(new URL("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt").openStream(), StandardCharsets.UTF_8))
        .lines()
        .collect(Collectors.groupingBy(s -> Stream.of(s.split("")).sorted().collect(Collectors.joining()), Collectors.toList()))
        .entrySet().stream()
        .collect(Collectors.groupingBy(e -> e.getValue().size(), TreeMap::new, Collectors.toList()))
        .lastEntry().getValue()
        .stream().map(Map.Entry::getValue)
        .sorted(Comparator.comparing(s -> s.get(0)))
        .map(n -> n.stream().sorted().collect(Collectors.joining(" ")))
        .forEach(System.out::println);

Upvotes: 1

Related Questions