简体   繁体   中英

Find all common elements in two lists

I am trying to find the common elements in my ArrayList "list1"

List<LocalDate> list1 = new ArrayList<> ();
for (LocalDate d = dateFrom; !d.isAfter(dateTo); d = d.plusDays(1)) {
      dates.add(d);

that consists of all dates between "dateFrom" and "dateTo" and my list "list2"

List<LocalDate> list2 = Arrays.asList(dateTime);

where dateTime is a variable that stores only the dates from a textfile with the following structure:

1946-01-12;07:00:00;-1.3;G
1946-01-12;13:00:00;0.3;G
1946-01-12;18:00:00;-2.8;G
1946-01-13;07:00:00;-6.2;G
1946-01-13;13:00:00;-4.7;G
1946-01-13;18:00:00;-4.3;G

I tried using list2.retainAll(list1); in order to find all the dates in list2 that is also in list1, but I think my problem is that list2 is not an arraylist. How can I fix that?

private static List<WeatherDataHandler> weatherData = new ArrayList<>();
public void loadData(String filePath) throws IOException {
//Read all data
    List<String> fileData = Files.readAllLines(Paths.get("filePath"));

    Map<String, Long> frequencyMap = new LinkedHashMap<>();

    LocalDate dateFrom = LocalDate.of(1946,01,12);
    LocalDate dateTo = LocalDate.of(1946, 01, 14);

    List<LocalDate> list1 = new ArrayList<> ();
    for (LocalDate d = dateFrom; !d.isAfter(dateTo); d = d.plusDays(1)) {
      dates.add(d);

    }

    for(String str : fileData) {
        List<String> parsed = parseData(str);
        LocalDate dateTime = LocalDate.parse(parsed.get(0));
        LocalTime Time = LocalTime.parse(parsed.get(1));
        double temperature = Double.parseDouble(parsed.get(2));
        String tag = parsed.get(3);

        WeatherDataHandler weather = new WeatherDataHandler(dateTime, Time, temperature, tag);
        weatherData.add(weather);

        List<LocalDate> list2 = Arrays.asList(dateTime);

        list2.retainAll(list1); 

        String strDate = list2.toString();
        frequencyMap.compute(strDate,
                (date, count) -> count == null ? 1 : count + 1);
    }

    for (Map.Entry<String, Long> entry : frequencyMap
            .entrySet()) {
        if (entry.getValue() < 24){
        System.out.println(
                entry.getKey() + ": " + (24-entry.getValue()));
    }}

You can do it as follows:

List<LocalDate> commonList = new ArrayList<LocalDate>();
for (LocalDate date : list1) {
    if(list2.contains(date)) {
        commonList.add(date);
    }
}
System.out.println("Common elements: " + commonList)

[Update]

Replace

if (entry.getValue() < 24)

with

if (entry.getValue() < 24 && !entry.getKey().equals("[]"))

in your code to get rid of something like []: 23 .

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