简体   繁体   中英

Is there a way loop through 2 arrays and print the element of array 1 if it contains the substring of any element from array 2?

The problem I am trying to solve is how to read lines from a text file and add it to an array. Then sort each element from this new array by the date that is also in each element. I will explain so its easier to understand but will explain what I am doing.

My text file (First column is name, second is Date of birth and last is the date the person died):

sarah jones,1966-12-02,2018-12-04

matt smith,1983-02-03,2020-03-02

john smith,1967-03-04,2017-04-04

I want to sort this file and output it to another file (testing by printing to console at the moment) by sorting it by the date the person died. A way I thought of doing this is to read each line and pass it to an array. Then read each element within the array, split it and then save the date the person died to another array. Then sort the array that has the death dates, loop through both arrays by seeing if the first element of the death date array matches the first element of the first line in the text file, if so then write it to another file. If not then go to the next line.

For example

BufferedReader reader = new BufferedReader(new FileReader("input_text.txt"));
PrintWriter outputStream = new PrintWriter(new FileWriter("output.txt",true));

ArrayList<String> lines = new ArrayList<String>();
ArrayList<String> substr_date = new ArrayList<String>();

String currentline = reader.readLine();

while(currentline !=null){
        String a_line[] = currentline.split(",");
        substr_date.add(a_line[2])
        lines.add(currentline);
        currentline = reader.readLine();
}

Collections.sort(substr_date);
for(String date : substr_date){
        for(String line : lines){
                if(line.contains(date)){
                        System.out.println(line);
         }
    }
}

I expect the output to be:

john smith,1967-03-04,2017-04-04

sarah jones,1966-12-02,2018-12-04

matt smith,1983-02-03,2020-03-02

The results are initially in order but then some lines are repeated multiple times and then the whole text file in repeated to the console and becomes a mess. I am not sure how to go about doing this. I am new to java and not sure if I asked this question properly either so if you need any more info please ask.

The way you are doing is a long shot. You can do this in much simpler way. You could pass a comparator to the Collections.sort() method like this.

Collections.sort(substr_date, new Comparator<String>{
   @Override
   public int compare(String str1, String str2){
       String dd1 = str1.split(",")[2];
       String dd2 = str2.split(",")[2];
       return dd1.compareTo(dd2);
   }
});

Comparing dates like this, though, is not a good approach. You should convert the date string to LocalDateTime and then use isBefore() or isAfter() to compare them. For ex,

public int compare(String str1, String str2){
    DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd")
    LocalDateTime d1 = LocalDateTime.parse(str1.split(",")[2],format);
    LocalDateTime d2 = LocalDateTime.parse(str2.split(",")[2],format);
    return d1.isBefore(d2)?-1:(d1.isAfter(d2)?1:0);
}

I would create class for objects which you can insert into a list and then define a comparator on this class which you can use to sort.

Here is an example of the class you could define:

static class DeceasedPerson {
    String name;
    LocalDate birthDate;
    LocalDate deathDate;

    DeceasedPerson(String name, LocalDate birthDate, LocalDate deathDate) {
        this.name = name;
        this.birthDate = birthDate;
        this.deathDate = deathDate;
    }

    @Override
    public String toString() {
        return name + ", " + birthDate + ", " + deathDate;
    }
}

Then you could simply load objects based on this class into a list which you sort using a comparator. Here is some sample code you can run with the class defined above:

public static void main(String[] args) {
    String input =
            "matt smith,1983-02-03,2020-03-02\n" +
                    "sarah jones,1966-12-02,2018-12-04\n" +
                    "john smith,1967-03-04,2017-04-04\n";
    List<DeceasedPerson> deceasedPersonList = new ArrayList<>();
    try (Scanner scanner = new Scanner(input)) {
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            String[] array = line.split(",");
            DeceasedPerson deceasedPerson = new DeceasedPerson(array[0],
                    LocalDate.parse(array[1]), LocalDate.parse(array[2]));
            deceasedPersonList.add(deceasedPerson);
        }
    }
    deceasedPersonList.sort(Comparator.comparing(o -> o.deathDate));
    deceasedPersonList.forEach(System.out::println);
}

If you run the code above using the DeceasedPerson class you should see on the console the following output:

john smith, 1967-03-04, 2017-04-04
sarah jones, 1966-12-02, 2018-12-04
matt smith, 1983-02-03, 2020-03-02

You could actually also use a TreeSet instead of a List in the main method above and achieve the same results. Here is a move concise alternative:

public static void main(String[] args) {
    String input =
            "matt smith,1983-02-03,2020-03-02\n" +
                    "sarah jones,1966-12-02,2018-12-04\n" +
                    "john smith,1967-03-04,2017-04-04\n";
    Set<DeceasedPerson> deceasedPersonList = new TreeSet<>(Comparator.comparing(o -> o.deathDate));
    try (Scanner scanner = new Scanner(input)) {
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            String[] array = line.split(",");
            DeceasedPerson deceasedPerson = new DeceasedPerson(array[0],
                    LocalDate.parse(array[1]), LocalDate.parse(array[2]));
            deceasedPersonList.add(deceasedPerson);
        }
    }
    deceasedPersonList.forEach(System.out::println);
}

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