0

I am still learning how to translate C# code using LinQ into standard Java. I am currently working on the following.

// For reference
private SortedSet<Message> _set = new SortedSet<Message>(new MessageSentTimeStampComparer())

List<Message> messages = new List<Message>();
//
lock (_setLock)
{
   messages.AddRange(_set.Where((m) => long.Parse(m.Attribute[0].Value) < epochWindowTime));
   _set.RemoveWhere((m) => long.Parse(m.Attribute[0].Value) < epochWindowTime);
}

If I understand this correctly, these two lines of code both iterate over the entire SortedSet _set.

The first line adds all of the messages in _set where attribute 0 of each message is less than the epochWindowTime.

The second line removes any message from _set where the message's attribute 0 is less than the epochWindowTime.

If I were to replicate this functionality in Java I would do something like the following

_setLock.lock();

Iterator<Message> _setIter = _set.iterator();
//TODO

while(_setIter.hasNext())
{
    Message temp = _setIter.next();

    Long value = Long.valueOf(temp.getAttributes().
         get("Timestamp"));
    if(value.longValue() < epochWindowTime)
    {
        messages.add(temp);
        _set.remove(temp);
    }
}

_setLock.unlock();

Is my understanding and implementation correct?

JME
  • 2,293
  • 9
  • 36
  • 56
  • 1
    Not a Java guy, but it appears you got the basics right. Not being a Java guy, I can't tell you if `Message temp=_setIter.next()` will make a copy or just point to the current copy, and I'm not familiar enough to tell you if `_set.remove(temp)` will throw an error because you are modifying the collection while iterating it or not. And of course, your code assumes the first attribute is the timestamp attribute. – Robert McKee Jun 10 '13 at 20:34
  • There is a subtle difference between literally translating and interpreting (or paraphrasing). Looks like you're leaning to the latter. You interpret a piece of code and convert it to a functional equivalent. A different approach could be to use/create equivalents for .Net constructs (like LINQ) and try to obtain a more 1:1 conversion. As for LINQ, some idea's could be found [here](http://stackoverflow.com/q/1217228/861716). – Gert Arnold Jun 10 '13 at 21:20

0 Answers0