[英]Find all common elements in two lists
I am trying to find the common elements in my ArrayList "list1"我试图在我的 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"包含“dateFrom”和“dateTo”以及我的列表“list2”之间的所有日期
List<LocalDate> list2 = Arrays.asList(dateTime);
where dateTime is a variable that stores only the dates from a textfile with the following structure:其中 dateTime 是一个变量,它仅存储来自具有以下结构的文本文件的日期:
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);
我尝试使用
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.为了找到 list2 中所有也在 list1 中的日期,但我认为我的问题是 list2 不是一个数组列表。 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
.在您的代码中删除
[]: 23
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.