-2

Please help me implement a .map function that works on the List classes/interfaces in Java 7. I cannot use any features of Java 8 or external libraries. This needs to be similar to Scala's function in its implementation and return values if possible. (Maybe impossible).

This is a different question than the so-called "duplicate" because it asks for something different entirely. I have tried to find an implementation of this function or pointers on putting one together, with no luck. I have asked here and had no luck in implementing suggestions or code that was given. It has been said that this is a "trivial" function, and yet, it evades me.

1

2 Answers 2

0

To do a groupBy in Java 7 you have do something like this.

Map<K, List<V>> map = new HashMap<>();
for(V v : charges) {
    K k = v.getCC();
    List<V> values = map.get(k);
    if (values == null)
        map.put(k, values = new ArrayList<>());
    values.add(v);
}

Of course this is much easier in Java 8.

Sign up to request clarification or add additional context in comments.

2 Comments

@m482 so if you already have an implementation, what was the question? Or have you changed the question completely? The Stream.map() is trivial but only really makes sense in the context of a stream and a lambda, so I am not sure what you are asking.
The question is how can I write a List.map() implementation in Java? Thank you.
0

A different answer for a different question.

The question is how can I write a List.map() implementation in Java?

In Java 7 you would use a loop and you would place inside that loop the code which would appear in the mapping (or filter, or flatMap)

e.g. in Java 8 you might write.

List<String> words = ..
List<String> allLower = words.stream()
                             .map(s -> s.toLowerCase())
                             .collect(Collectors.toList());

in Java 7 you would place the toLowerCase in to the loop.

List<String> words = ..
List<String> allLower = new ArrayList<>(words.size());
for (String word : words) 
    allLower.add(word.toLowerCase()); // map(x -> ?) goes here.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.