Difference between map and filter on a java collection stream

ⅰ亾dé卋堺 提交于 2020-11-28 02:41:05

问题


Suppose there is a list say

List<String> myList = new ArrayList<String>();
myList.add("okay");
myList.add("omg");
myList.add("kk");

I am doing this:

List<String> fianllist = myStream.map(item -> item.toUpperCase()).filter(item
->item.startsWith("O")).collect(Collectors.toList());

My question is what the difference between map and filter as both can take a lambda expression as a parameter. Can some one please explain?


回答1:


By using map, you transform the object values.

The map operation allows us to apply a function, that takes in a parameter of one type, and returns something else.

Filter is used for filtering the data, it always returns the boolean value. If it returns true, the item is added to list else it is filtered out (ignored) for eg :

List<Person> persons = …
Stream<Person> personsOver18 = persons.stream().filter(p -> p.getAge() > 18);

For more details on this topic you can visit this link




回答2:


Filter takes a predicate as an argument so basically you are validating your input/collection against a condition, whereas a map allows you to define or use a existing function on the stream eg you can apply String.toUpperCase(...) etc. and transform your inputlist accordingly.



来源:https://stackoverflow.com/questions/37154380/difference-between-map-and-filter-on-a-java-collection-stream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!