Operacje na plikach, sortowanie słów w j Polskim -- Optymalizacja kodu

0

Co zrobilibyście lepiej ??

package pliki;

/*
Zbiór zadań 7
Zad 8

Zad 8
W dwóch przygotowanych przez Ciebie plikach tekstowych znajdują się w
każdym wierszu słowa. Nie wiemy, ile jest słów w każdym pliku. Napisz
program, który do trzeciego pliku zapisuje tylko te słowa, które
pojawiły się jednocześnie w dwóch plikach i zawierają w sobie więcej
spółgłosek niż samogłosek. Ze słów w trzecim pliku tekstowym utwórz
jeden napis, w którym kolejne słowa są oddzielone przecinkami i
występują w kolejności alfabetycznej.
 */


import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.text.Collator;
import java.util.Arrays;
import java.util.Locale;
import java.util.Scanner;

public class Zad2 {

    static void thirdFile(String[][] arr1, String[][] arr2) {

        int vovelNumber = 0;
        int consonantsNumber = 0;

        try (FileWriter fileWriter = new FileWriter("zad8File3")) {
            PrintWriter printWriter = new PrintWriter(fileWriter);


            for (int i = 0; i < arr1.length; i++) {
                for (int j = 0; j < arr1[i].length; j++) {

                    if (contains(arr2, arr1[i][j])) {
                        vovelNumber = vowelNumber(arr1[i][j]);
                        consonantsNumber = arr1[i][j].length() - vovelNumber;

                        if (consonantsNumber > vovelNumber) {
                            printWriter.print(arr1[i][j]);
                            printWriter.print(" ");
                        }
                    }
                }
            }

        } catch (Exception e) {
            throw new IllegalArgumentException("filewriter err");
        }
    }

    static int vowelNumber(String txt) {

        int counter = 0;
        char[] arr = txt.toCharArray();

        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == 'a' || arr[i] == 'e' || arr[i] == 'i' || arr[i] == 'o' || arr[i] == 'u' || arr[i] == 'y') {
                counter++;
            }
        }
        return counter;
    }


    static boolean contains(String[][] arr, String word) {

        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                if (arr[i][j].equals(word)) {
                    return true;
                }
            }
        }
        return false;
    }

    static String[][] readFile(String fileName) {

        try (FileReader fileReader = new FileReader(fileName)) {
            Scanner sc = new Scanner(fileReader);

            int linesNumber = linesNumber(fileName);
            String[][] arr = new String[linesNumber][];

            for (int i = 0; i < linesNumber; i++) {
                arr[i] = sc.nextLine().split(" ");
            }
            sc.close();

            return arr;
        } catch (Exception e) {
            throw new IllegalArgumentException("filereader err");
        }
    }


    static int linesNumber(String fileName) {

        try (FileReader fileReader = new FileReader(fileName)) {
            Scanner sc = new Scanner(fileReader);
            int counter = 0;

            while (sc.hasNextLine()) {
                counter++;
                sc.nextLine();
            }
            sc.close();

            return counter;
        } catch (Exception e) {
            throw new IllegalArgumentException("err");
        }
    }

    public static void main(String[] args) {
        String[][] arrFile1 = readFile("zad8File1");
        String[][] arrFile2 = readFile("zad8File2");

        System.out.println("file1: " + Arrays.deepToString(arrFile1));
        System.out.println("file2: " + Arrays.deepToString(arrFile2));

        thirdFile(arrFile1, arrFile2);
        String[][] arrFile3 = readFile("zad8File3");
        System.out.println("file3: " + Arrays.deepToString(arrFile3));

        Locale.setDefault(new Locale("pl", "PL"));
        Arrays.sort(arrFile3[0], Collator.getInstance());

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < arrFile3[0].length; i++) {
            sb.append(arrFile3[0][i] + ", ");
        }

        sb.delete(sb.length() - 2, sb.length() - 1);

        System.out.println(sb);
    }

}


1

Użyłbym dobrodziejstw Javy 8 :)

public class Solution {

    private static final Set<Integer> VOWELS = "aeyioąęuó".chars().boxed().collect(Collectors.toSet());

    public static void main(String[] args) throws Exception {
        Files.writeString(Paths.get("f3.txt"),
            Stream.of("f1.txt", "f2.txt")
                .flatMap(Solution::readFile)
                .collect(
                    Collectors.groupingBy(
                        Word::getWord,
                        Collectors.collectingAndThen(
                            Collectors.mapping(Word::getFile, Collectors.toSet()),
                            Set::size
                        )
                    )
                )
                .entrySet()
                .stream()
                .filter(it -> it.getValue() > 1)
                .map(Map.Entry::getKey)
                .filter(Solution::isWordValid)
                .sorted()
                .collect(Collectors.joining(",")),
            StandardOpenOption.CREATE,
            StandardOpenOption.TRUNCATE_EXISTING
        );
    }
    
    private static Stream<Word> readFile(String file) {
        try {
            return Files.lines(Paths.get(file))
                .map(line -> line.split("\\s+"))
                .flatMap(Arrays::stream)
                .distinct()
                .map(word -> new Word(file, word));
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }

    private static boolean isWordValid(String word) {
        int length = word.length();
        long vowels = word.chars().boxed().filter(VOWELS::contains).count();
        return (length - vowels) > vowels;
    }

    static class Word {
        final String file;
        final String word;
        Word(String file, String word) {
            this.file = Objects.requireNonNull(file);
            this.word = Objects.requireNonNull(word);
        }
        String getFile() { return file; }
        String getWord() { return word; }
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Word word1 = (Word) o;
            return Objects.equals(file, word1.file) && Objects.equals(word, word1.word);
        }
        public int hashCode() {
            return Objects.hash(file, word);
        }
    }
}

1 użytkowników online, w tym zalogowanych: 0, gości: 1