简体   繁体   English

在Java中同时迭代两个TreeMap

[英]Iterate over two TreeMap at the same time in Java

I have two maps: 我有两张地图:

 Map<Date, List<Journey>> journeyMap = new TreeMap<Date, List<Journey>>
 Map<Date, List<Job>> jobMap = new TreeMap<Date, List<Job>>

I used TreeMap because that means they're sorted by date but I want to go through both maps at the same time, get the values of Journey/Job, then do some work. 我使用TreeMap是因为这意味着它们按日期排序,但是我想同时浏览两个地图,获取Journey / Job的值,然后做一些工作。

I think i could use generics, storing the Job/Journey as an Object, then checking the instanceOf but I'm not sure if thats the solution? 我认为我可以使用泛型,将Job / Journey存储为一个对象,然后检查instanceOf,但是我不确定这是否是解决方案?

Thanks. 谢谢。

You're making an assumption that these maps are having values sorted in the very same way, but this is definitely not correct. 您假设这些映射的值以相同的方式排序,但这绝对是不正确的。 At least if you want to write a logic like this you need to declare the same implementing class as a reference: 至少如果要编写这样的逻辑,则需要声明相同的实现类作为引用:

TreeMap<Date, List<Journey>> journeyMap = new TreeMap<Date, List<Journey>>
TreeMap<Date, List<Job>> jobMap = new TreeMap<Date, List<Job>>

but believe me you don't want to do it. 但请相信我,您不想这样做。

You're right! 你是对的! Instead doing 2 maps create 1, holding pair of Job/Journey objects - create a JobJourneyHolder class which holds both objects, this will be a good solution. 取而代之的是创建2个映射,以创建1个,同时持有一对Job / Journey对象-创建一个JobJourneyHolder类,其中包含两个对象,这将是一个很好的解决方案。

Yes, defining a new class for that is definitely the solution, because it composes related objects together, which is very welcomed in OOP. 是的,为此定义一个新的类绝对是解决方案,因为它将相关的对象组合在一起,这在OOP中非常受欢迎。 And you should not forget to implement hashCode() and equals() methods to make such classes work properly in Java collections: 而且,您不应忘记实现hashCode()equals()方法,以使此类在Java集合中正常工作:

public final class JourneyJob {
   final Journey journey;
   final Job job;

   public JourneyJob(Journey journey, Job job) {
       if (journey == null || job == null)
            throw new NullPointerException();
       this.journey = journey;
       this.job = job;
   }

   public int hashCode() {
       return Objects.hash(journey, job);
   }

   public boolean equals(JourneyJob other) {
       return other.job.equals(job) && other.journey.equals(journey);
   }
}

To add elements to common Map: 要将元素添加到通用地图:

Map<Date, List<JourneyJob>> map = new TreeMap<>();
...

if (map.contains(date)) {
   map.get(date).add(new JourneyJob(journey, job));
} else {
   map.put(date, new ArrayList<>(Arrays.asList(new JourneyJob(journey, job)));
}

...

To retrieve JourneyJob objects: 检索JourneyJob对象:

for (List<JourneyJob> jjList : map.values()) {
    for (JourneyJob jj : jjList) {
       journey = jj.journey;
       job = jj.job;
       //... do your work here
    }
}

Or, if you use Java 8, this can be done using nested forEach() : 或者,如果您使用Java 8,则可以使用嵌套的forEach()完成此操作:

map.values().stream().forEach(list ->
    list.stream().forEach(jj -> {
       Journey journey = jj.journey;
       Job job = jj.job;
       //... do your work here
    })
);

Even though the others are right, that there are better, safer and more comfortable ways to achive whatever you want, it is possible to iterate over (the entries of) two Maps (aka Collections) at the same time. 即使其他方法是正确的,也有更好,更安全,更舒适的方法来实现您想要的任何东西,但是可以同时遍历两个Map(又称为Collection)(即Collections)。

//replace keySet() with your favorite method in for-each-loops
Iterator<Date> journeyIterator = journeyMap.keySet().iterator()
Iterator<Date> jobIterator = jobMap.keySet().iterator();
while(journeyIterator.hasNext() && jobIterator.hasNext()){
    Date journeyDate = journeyIter.next()
    Date jobDate = jobIterator.next();
    //... do whatever you want with the data
}

This code does explicitly, what a for-each-loop can do implicitly for one Collection. 这段代码明确地执行了一个for-each-loop可以隐式执行一个Collection的操作。 It retrieves the Iterator and gets the element from the Collection from it, much like reading a file. 它检索Iterator并从其中获取Collection中的元素,就像读取文件一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Java中遍历对象的TreeMap(不是字符串!) - Iterate over a TreeMap of Objects (not Strings!!) in Java 如何在Java中使用多个线程迭代一个Collection,其中没有两个线程迭代在Collection的同一部分? - How to use multiple threads in Java to iterate over a Collection where no two threads ever iterate over the same part of the Collection? 我如何迭代增加 TreeMap - How could I iterate over increasing TreeMap 从键值对开始迭代Java中的Map(特别是TreeMap) - Iterate over Map (Specifically TreeMap) in Java starting from a key-value pair 如何在Java数组中一次迭代4个以上的元素? - How to iterate over 4 elements at a time in an array in Java? 如何从 Java TreeMap 中的给定键进行迭代 - How to iterate from a given key in Java TreeMap Java TreeMap时间复杂度-LowerKey - Java TreeMap time complexity - lowerKey java同时迭代list和addFirst - java iterate list and addFirst at the same time Java - 迭代 arrayList 并将 250k 字插入到 treeMap 中需要花费大量时间 - Java - Iteration over arrayList & Insertion of 250k words into treeMap is taking huge time 如何在不创建临时对象的情况下遍历嵌套的TreeMap - How to iterate over a nested TreeMap without creating temporary Objects
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM