Connect and share knowledge within a single location that is structured and easy to search. Java MCQ Multiple Choice Questions and Answers OOPsThis collection of Java Multiple Choice Questions and Answers (MCQs): Quizzes & Practice Tests with Answer focuses on Java OOPs. Maybe will be useful for somebody. We are required to write a JavaScript function that takes in two such arrays. ArrayList is a part of the collection framework and is present in java.util package. Filter by Object properties uses java operators. Java MCQ Multiple Choice Questions and Answers OOPs, How to Set JFrame in Center of the Screen, How to Change the Size of a JFrame(window) in Java, JMenu, JMenuBar and JMenuItem Java Swing Example, Dialog boxes JOptionPane Java Swing Example, Event and Listener Java Swing Example, How to Change Font Size and Font Style of a JLabel, How to Count the Clicks on a Button in Java, How to Get Mouse Position on Click Relative to JFrame, How to Change Look and Feel of Swing Application, How to display an image on JFrame in Java Swing, How to Add an Image to a JPanel in Java Swing, How to Change Font Color and Font Size of a JTextField in Java Swing, How to dynamically filter JTable from textfield in Java, How to get Value of Selected JRadioButton in Java, How to get the selected item of a JComboBox in Java, How to insert and retrieve an image from MySQL database using Java, How to Create a Vertical Menu Bar in Java Swing, How to add real-time date and time in JFrame, Use Enter key to press JButton instead of mouse click, How to Clear JTextArea by Clicking JButton, How to use JFileChooser to display image in a JFrame, How to Get the State of JCheckBox in Java Swing, How to link two JComboBox together in Java Swing, How to Display Multiple Images in a JFrame, How to draw lines, rectangles, and circles in JFrame, How to Display a Webpage Inside a Swing Application, Difference between JTextField and JFormattedTextField in Java, How to Make JTextField Accept Only Alphabet, How to Make JTextField Accept Only Numbers, How To Limit the Number of Characters in JTextField, How to Capitalize First Letters in a JTextField in Java, Convert to Uppercase while Writing in JTextField, How to Add a Listener for JTextField when it Changing, How to Disable JButton when JTextField is Empty, How to Make JButton with Transparent Background, How to Change the Border of a JFrame in Java, How to Remove Border Around JButton in Java, How to Remove Border Around Text in JButton, How to Change Border Color of a JButton in Java Swing, How to Change the Background Color of a JButton, How to Change the Position of JButton in Java, How to Print a JTable with Image in Header, How to Delete a Row in JTable using JButton, How to Get Selected Value from JTable in Java, How to Sort JTable Column in Java [2 Methods], How to Alternate Row Color of JTable in Java, How to Change Background Color of JTable Cell on Mouse Click, How to Count Number of Rows and Columns of a JTable, How to Add Row Dynamically in JTable Java, How to Create Multi-Line Header for JTable, How to Set Column Width in JTable in Java, How to Know Which Button is Clicked in Java Swing, How to Close a JFrame in Java by a Button, How to add onclick event to JButton using ActionListener in Java Swing, How to add checkbox in menuItem of jMenu in Java Swing, How to create a right-click context menu in Java Swing, How to Create Hyperlink with JLabel in Java, How to add an object to a JComboBox in Java, How to add and remove items in JComboBox in Java, How to Add Image Icon to JButton in Java Swing, How to Create Multiple Tabs in Java Swing, How to Set Background Image in Java Swing, How to Delete a Selected Row from JTable in Java, How to Change Background Color of a Jbutton on Mouse Hover, Detect Left, Middle, and Right Mouse Click Java, How to Create Executable JAR File in Java, Java MCQ Multiple Choice Questions and Answers Data Types and Variables Part 1, Java MCQ Multiple Choice Questions and Answers Data Types and Variables Part 2, How to get the length or size of an ArrayList in Java, How to initialize a list with values in Java, How to Extract Text Between Parenthesis in Java, How to remove text between tags using Regex in Java, How to Get String Between Two Tags in Java, How to extract email addresses from a string in Java, How to extract numbers from a string with regex in Java, How to calculate the average of an ArrayList in Java, How to find the sum of even numbers in Java, How to read the contents of a file into a String in Java, How to read the first line of a file in Java, How to read a specific line from a text file in Java, How to fill a 2D array with numbers in Java, How to add a character to a string in Java, How to extract numbers from an alphanumeric string in Java, How to check if an element exists in an array in Java, Phone number validation using regular expression (regex) in Java, How to determine the class name of an object in Java, How to delete a directory if exists in Java, How to Check if a Folder is Empty in Java, How to check Java version in Windows, Linux, or Mac, How to remove XML Node using Java DOM Parser, How to update node value in XML using Java DOM, How to change an attribute value in XML using Java DOM, How to add child node in XML using Java DOM, How to iterate through an ArrayList in Java, Java Program to Check Whether a Date is Valid or Not, How to check if a key exists in a HashMap in Java, How to pause a Java program for X seconds, How to Count Number of Elements in a List in Java, How to run a batch file from Java Program, How to convert an integer to a string in Java, How to Declare and Initialize two dimensional Array in Java, How to get values and keys from HashMap in Java, How to get the first and last elements from ArrayList in Java, How to extract a substring from a string in Java, How to search a character in a string in Java, How to convert a file into byte array in Java, How to change the permissions of a file in Java, How to list contents of a directory in Java, How to move a file from one directory to another in Java, How to append content to an existing file in Java, How to create a directory if it does not exist in Java, How to get the current working directory in Java, How to Convert Array to ArrayList in Java, How to Convert ArrayList to Array in Java, How to check if a string contains only numbers in Java, How to check if a character is a letter in Java, How to remove multiple spaces from a string in Java, How to Convert a String to a Date in Java, How to round a number to n decimal places in Java, How to Set the Java Path Environment Variable in Windows 10, How to Compile and Run your Java Program in Command Line, Why Java Doesnt Support Multiple Inheritance, Write a Java Program to Calculate the Area of Circle, Write a Java Program to Calculate the Area of Triangle, Write a Java Program to Calculate the Area of Square, Java Program to Calculate Area of Rectangle, Java Program to Print Multiplication Table, Write a Java Program to Calculate the Multiplication of Two Matrices, Write a Java Program to Check Whether an Entered Number is Odd or Even, Binary Search in Java: Recursive + Iterative, How to search a particular element in an array in Java, How to convert a char array to a string in Java, Java Program to Convert Decimal to Binary, Java Program to Convert Decimal to Hexadecimal, Java Program to Convert Binary Number to Decimal, Write a Java Program to Multiply Two Numbers, How to Convert ASCII Code to String in Java, How to Get the ASCII Value of a Character in Java, How to Check If a Year is a Leap Year in Java, Check if a number is positive or negative in Java, How to Find the Smallest of 3 Numbers in Java, Java Program to Find Largest of Three Numbers, Factorial Program In Java In 2 Different Ways, How to Reverse a String in Java in 2 different ways, Write a Java Program to Add Two Binary Numbers, Write a Program to Find the GCD of Two Numbers in Java. For example, let say Contact class has three properties: street, city, phone. PTIJ Should we be afraid of Artificial Intelligence? Find centralized, trusted content and collaborate around the technologies you use most. Users can extend it for thread safety/parallelism. StreamFilterExample5.java import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.Collection; public class StreamFilterExample5 { Guide to MapStruct in Java. How do I convert a String to an int in Java? The same that Rahel has answered expect for the unsafe stream() ? Rachmaninoff C# minor prelude: towards the end, staff lines are joined together, and there are two end markings, Is email scraping still a thing for spammers, "settled in as a Washingtonian" in Andrew's Brain by E. L. Doctorow, Ackermann Function without Recursion or Stack. How to Sort an Array of Strings in JavaScript. List of land cover classes in particular area and use them as an item for ui.Select, List for ui.Select from Modis land cover classes in Earth Engine, List of Dates in GEE giving wrong results, GEE: Indexing a List of Lists inside a property of a FeatureCollection. There are plenty of ways to achieve this. What is the ideal amount of fat and carbs one should ingest for building muscle? How to add an element to an Array in Java? Easiest way to convert a List to a Set in Java, Retrieving a List from a java.util.stream.Stream in Java 8, Filter Java Stream to 1 and only 1 element. To filter an array of objects based on a property in JavaScript, you can either iterate over the array or use the Array class' .filter () function. A style sheet consists of a list of rules. You can create list of functions that extract properties, than use it in your filter method: Thanks for contributing an answer to Stack Overflow! Predicate<Person> byAge = person -> person.getAge () > 30; This predicate returns elements with age greater than thirty. Allows you to filter the list of clusters based on certain criteria; for example, filtering by cluster creation date and time or by status. In this tutorial, you will learn how to sort an ArrayList of Objects by property using comparable and comparator interface. 2. In this article, we will learn Java Stream Filter API. regex remove everything after last slash jan glover emmerdale actress. are patent descriptions/images in public domain? How to draw a truncated hexagonal tiling? "Filters a list to only the elements that match the given filter. Seems like you need full-text search in your database. Using the Stream API. Why don't we get infinite energy from a continous emission spectrum? Is lock-free synchronization always superior to synchronization using locks? Search for jobs related to Java filter list of objects by property or hire on the world's largest freelancing marketplace with 21m+ jobs. This doesn't help for a list of dictionaries. rev2023.3.1.43266. Do flight companies have to make it clear what visas you might need before selling you tickets? Output. The example filters a list of person beans using the Apache CollectionUtils PriceType is an Enum, that's either PriceType.SELLING or PriceType.BUYING. One of the alternatives we have is to write a filter that maintains the state. 2. Not the answer you're looking for? and set of utility classes that work with any JDK compatible Collections, 3. java stream filter list of objects by property java get object in list by attribute java list find stream java list find matching element by property java get object that matches condition java find in a list all objects that match property value get condition java find objectr in list java find object by attribute in list java We are required to devise a way to filter an array of objects depending on a string keyword. Remove duplicates from a list of objects based on property in Java 8, Java 8 stream - merge two collections keeping it unique by specific field, How to filter 2 huge list with millions of item in it with same id, JAVA : How to remove duplicates from list using stream, Select distinct objects by custom field via Stream API, How to remove duplicates using Java 8 streams based on criteria, remove elements with repeated attribute using lambda expressions, filter duplications by property name with java stream filter, Remove duplicates using lambda function in Java 8. Anonymous Classes in JavaAnonymous Classes (or Anonymous Inner Classes) are nameless classes, more precisely, a class with no name thats defined and initialized at the same time. It was edited while I was typing this. So I would suggest using this : Thanks for contributing an answer to Stack Overflow! We can use Intstream and map the array elements based on the index. Did the residents of Aneyoshi survive the 2011 tsunami thanks to the warnings of a stone marker? The toString method gives a string representation of Required fields are marked *. Applications of super-mathematics to non-super mathematics. This library also contains a predicate class: org.apache.commons.collections4.Predicate with a test method evaluate(), which decides whether a property applies to the transferred object. This may work for, @Torque that is not the case (anymore? To subscribe to this RSS feed, copy and paste this URL into your RSS reader. List<int> filtered = vals.FindAll (e => e > 0); The FindAll method retrieves all the elements that match the conditions defined by the specified predicate. Is email scraping still a thing for spammers, The number of distinct words in a sentence. Filtering a Collection with Streams For the sake of simplicity, in all the examples our objective will be to create a method that retrieves only the even numbers from a Collection of Integer values. com.google.common.base.Equivalence.wrap(S) and com.google.common.base.Equivalence.Wrapper.get() could help too. Your code here won't compile, in the filter 'a' is a student, which is does not have a stream() method. Below given is a function that accepts varargs parameters and returns a Predicate instance. Unfortunately the distinct() method has no such overload. 542), We've added a "Necessary cookies only" option to the cookie consent popup. I then created a stateful Predicate where I controled if the previous element was different from the current element, in that case I kept it. I know how to filter only at player level, like players.stream ().filter (p->p.number.equal (X)) or flatmap to get a list of players teams.stream ().flatmap (t->t.getPlayers ()) but how to I mix these lambda to get teams with a property filter on player? If you use .filter (distinctByKey (.)). Is quantile regression a maximum likelihood method? Filtering a Stream using Lambda Expression 2.2. So my question is, does Java or any other library support filtering the list with any matching property? What are examples of software that may be seriously affected by a time jump? PTIJ Should we be afraid of Artificial Intelligence? What are the differences between a HashMap and a Hashtable in Java? (adsbygoogle = window.adsbygoogle || []).push({}); If you dont want to add a utility library like Apache Commons or Google Guava to your project, you can of course write a simple method to filter a list yourself. What is behind Duke's ear when he looks back at Paul right before applying seal to accept emperor's request to rule? Retracting Acceptance Offer to Graduate School. Back to Stream Filter ; java2s.com | Demo Source and Support. How do I read / convert an InputStream into a String in Java? Stream partition answer by Tagir Valeev inspired me to use custom Collector which returns Map>. The $filter query parameter can also be used to retrieve relationships like members, memberOf, transitiveMembers, and transitiveMemberOf. Below are three DQL queries which will give you information on groups and acls. Launching the CI/CD and R Collectives and community editing features for How to filter a Java Collection (based on predicate)? Java 8 Streams - filter by a property of an object Ask Question Asked Viewed 940 times 1 I've got an Object called Price, that describes the selling and buying behaviour of an item. Asking for help, clarification, or responding to other answers. acknowledge that you have read and understood our, Data Structure & Algorithm Classes (Live), Data Structure & Algorithm-Self Paced(C++/JAVA), Android App Development with Kotlin(Live), Full Stack Development with React & Node JS(Live), GATE CS Original Papers and Official Keys, ISRO CS Original Papers and Official Keys, ISRO CS Syllabus for Scientist/Engineer Exam, Spring Boot - Start/Stop a Kafka Listener Dynamically, Parse Nested User-Defined Functions using Spring Expression Language (SpEL), Split() String method in Java with examples, Object Oriented Programming (OOPs) Concept in Java. @skiwi: do you think there is a way to implement, @Holger I may have been wrong there as I hadn't thought abou the overhead, And obviously it messes up the original order of the list, @DanielEarwicker this question is about "distinct by property". The CollectionUtils.filter method filters the result 1. Site design / logo 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA. In this case, the comparator is a lambda which defines the below parameters as follows: When the ArrayList is of a custom object type, then, in this case, we use two sorting methods by either Comparator or Comparable and in this case Collections.sort() cannot be used directly as it will give an error because it sorts only specific data-types and not user-defined types. Why does pressing enter increase the file size by 2 bytes in windows, How do I apply a consistent wave pattern along a spiral curve in Geo-Nodes. The rest of the logic is pretty straight Whatever you do, don't use delete to remove an item from an array. Late to the party but I sometimes use this one-liner as an equivalent: The expression is a Predicate but since the map is inline, it works as a filter. Jordan's line about intimate parties in The Great Gatsby? Browse other questions tagged, Where developers & technologists share private knowledge with coworkers, Reach developers & technologists worldwide. You can wrap the person objects into another class, that only compares the names of the persons. Convert a String to Character Array in Java. With the new Java 8 Streams API and the use of lambda expressions, lists or other collections can be filtered quite elegantly. If you want distinct based on two keys or may composite key, try this. For the Guava library, we use this dependency. Output. Why does the Angel of the Lord say: you have not withheld your son from me in Genesis? The is a Structure table called E1IDBW1 (for special instructions). ToStringBuilder, which is used in the toString method. CBSE Class 12 Computer Science; School Guide; All Courses; Tutorials. It's free to sign up and bid on jobs. My requirement is to filter a list of objects by a string matching any of the properties. Making statements based on opinion; back them up with references or personal experience. Would the reflected sun's radiation melt ice in LEO? Can patents be featured/explained in a youtube video i.e. It contains miscellaneous collection utility methods. How do I withdraw the rhs from a list of equations? collect (Collectors.toList ()); java lambda collections java-8 java-stream Share Improve this question Follow edited Oct 8, 2017 at 14:12 azro 51.7k 7 35 67 There are two plain objects for Student and Course like this: If we have a list of Students, how can we filter some of students by the name of their courses? Browse other questions tagged, Where developers & technologists share private knowledge with coworkers, Reach developers & technologists worldwide, I guess for better compatibility the argument should be, @java_newbie The Predicate instance returned by, @holandaGo It will fail if you save and reuse the Predicate instance returned by. Do German ministers decide themselves how to vote in EU decisions or do they have to follow a government line? For example I have a list of Person object and I want to remove people with the same name. Why don't we get infinite energy from a continous emission spectrum? 2. I had a situation, where I was suppose to get distinct elements from list based on 2 keys. Below code put users into map by its name attribute: Home java How to filter a list in Java. Here is the Java program to . The example filters a list of persons. The code calculates areas per land cover type and outputs a list of objects with two properties, 'code' i.e. Drift correction for sensor readings using a high-pass filter. Person class: Person class is as shown below. To subscribe to this RSS feed, copy and paste this URL into your RSS reader. Convert a String to Character Array in Java, Java Program to Get the First and the Last Element of a Linked List. I am aware of how java stream filter works, where i have to compare the input string with each property as below: However, if a class has 20+ properties and size of list 80,000+, comparing each property with the input string would affect the performance. By clicking Accept all cookies, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy. Users into map by its name attribute: Home Java how to filter a list of by! And outputs a list of dictionaries last element of a Linked list person! Pricetype is an Enum, that only compares the names of the properties sign and. Other questions tagged, Where I was suppose to get distinct elements from list based opinion! Before selling you tickets bid on jobs the Array elements based on the index java.util.stream.Collectors... Community editing features for how to Sort an Array in Java, Java to... Part of the Lord say: you have not withheld your son me... And I want to remove people with the new Java 8 Streams API and the use of lambda expressions lists. List with any matching property we 've added a `` Necessary cookies only '' option to the cookie popup! Accept emperor 's request to rule they have to follow a government line 'code ' i.e members... Did the residents of Aneyoshi survive the 2011 tsunami Thanks to the warnings of a list of rules or they. You will learn Java stream filter ; java2s.com | Demo Source and support help, clarification or... List with any matching property are three DQL queries which will give you information on groups and acls 2023 Exchange! Have to follow a government line the use of lambda expressions, lists or other can... Last element of a stone marker com.google.common.base.Equivalence.Wrapper.get ( java filter list of objects by property the is a of. Called E1IDBW1 ( for special instructions ) for special instructions ) stream API! A function that accepts varargs parameters and returns a Predicate instance contributions licensed under CC BY-SA method gives String. You have not withheld your son from me in Genesis of a stone marker stream filter ; java2s.com Demo. Can patents be featured/explained in a sentence differences between a HashMap and a Hashtable in Java of survive! Let say Contact class has three properties: street, city, phone collection ( based on Predicate?... Memberof, transitiveMembers, and transitiveMemberOf responding to other answers a high-pass filter list with any matching property Streams! To retrieve relationships like members, memberOf, transitiveMembers, and transitiveMemberOf the of. Custom Collector which returns map < A.id, list < a > > like members,,. Situation, Where developers & technologists share private knowledge with coworkers, Reach developers & technologists worldwide API and use. Line about intimate parties in the toString method gives a String representation of required fields are java filter list of objects by property * did residents! Returns map < A.id, list < a > > was suppose to get the First and use. Are three DQL queries which will give you information on groups and acls on groups acls! Tagir Valeev inspired me to use custom Collector which returns map < A.id, list < a > > Angel. To sign up and bid on jobs of a Linked list logo 2023 Stack Exchange ;. Warnings of a list of equations within a single location that is structured and easy to search, transitiveMembers and! 'S line about intimate parties in the Great Gatsby API and the use of lambda,... Within a single location that is not the case ( anymore is present java.util... Differences between a HashMap and a Hashtable in Java video i.e partition answer Tagir. ; Tutorials # x27 ; S free to sign up and bid on jobs and one. Program to get the First and the use of lambda expressions, or! Guide ; All Courses ; Tutorials need before selling you tickets and com.google.common.base.Equivalence.Wrapper.get ( ) tsunami to... Of a list of person beans using the Apache CollectionUtils PriceType is an Enum, that 's either PriceType.SELLING PriceType.BUYING! Convert a String to an Array in Java an arraylist of objects by property using comparable comparator! Java.Util.Collection ; public class StreamFilterExample5 { Guide to MapStruct in Java to search may composite key, try.. Rss feed, copy and paste this URL into your RSS reader RSS feed copy... Below code put users into map by its name attribute: Home Java how to an! Api and the use of lambda expressions, lists or other collections be. That is structured and easy to search sun 's radiation melt ice in LEO java2s.com | Demo Source and.... Objects into another class, that 's either PriceType.SELLING or PriceType.BUYING with two properties, 'code '.! Help too is email scraping still a thing for spammers, the number of distinct words a. Seal to accept emperor 's request to rule filter ; java2s.com | Demo and... Representation of required fields are marked * objects by property using comparable and comparator interface that either... ; public class StreamFilterExample5 { Guide to MapStruct in Java question is, does Java or any library. To write a JavaScript function that accepts varargs parameters and returns a Predicate instance slash. Would the reflected sun 's radiation melt ice in LEO CC BY-SA have! Science ; School Guide ; All Courses ; Tutorials synchronization using locks custom which! This may work for, @ Torque that is structured and easy to.! Using locks an InputStream into a String to Character Array in Java, Java Program to distinct. A situation, Where I was suppose to get the First and the last element a. The Great Gatsby technologists worldwide code put users into map by its name:... To only the elements that match the given filter use.filter ( distinctByKey (. ) ) jobs. And bid on jobs and community editing features for how to add an element to int... When he looks back at Paul right before applying seal to accept emperor 's request to?... Remove people with the new Java 8 Streams API and the last of. An Enum, that only compares the names of the Lord say: you have withheld... ' i.e that 's either PriceType.SELLING or PriceType.BUYING rhs from a continous spectrum. By Tagir Valeev inspired me to use custom Collector which returns map < A.id, list < a >. Like members, memberOf, transitiveMembers, and transitiveMemberOf Collectives and community editing features for how to Sort Array.. ) ), which is used in the toString method gives a String to Character Array in Java elements! R Collectives and community editing features for how to filter a list person! Predicate instance, @ Torque that is not the case ( anymore superior to synchronization using locks java.util.Collection ; class. Does n't help for a list of objects by a time jump expressions. By Tagir Valeev inspired me to use custom Collector which returns map < A.id, list a! To subscribe to this RSS feed, copy and paste this URL into RSS! Science ; School Guide ; All Courses ; Tutorials and R Collectives and community editing features how! Trusted content and collaborate around the technologies you use most example Filters a list equations. Wrap the person objects into another class, that 's either PriceType.SELLING or PriceType.BUYING do they have to a! Questions tagged, Where developers & technologists share private knowledge with coworkers, Reach developers & worldwide. Consent popup questions tagged, Where I was suppose to get the First and the use of lambda,!, and transitiveMemberOf one should ingest for building muscle structured and easy to search Structure table java filter list of objects by property E1IDBW1 ( special! Amount of fat and carbs one should ingest for building muscle Collector which returns map < A.id list. Two properties, 'code ' i.e quite elegantly to make it clear what you... Library support filtering the list with any matching property list of person object and I to! Or do they have to follow a government line I want to remove people the! That may be seriously affected by a String to Character Array in.... Suppose to get the First and the last element of a Linked list paste this URL into your RSS.... Between a HashMap and a Hashtable in Java toString method gives a String representation of fields... Into another class, that 's either PriceType.SELLING or PriceType.BUYING by property comparable! To filter a list in Java, Java Program to get the First and the use of expressions! Distinct based on 2 keys required to write a JavaScript function that takes in two arrays... Bid on jobs a thing for spammers, the number of distinct words a. Responding to other answers Duke 's ear when he looks back at Paul right before applying to. Your son java filter list of objects by property me in Genesis this tutorial, you will learn how vote. Around the technologies you use most decide themselves how to vote java filter list of objects by property EU or... ( ) method has no such overload a time jump ; user contributions licensed under CC BY-SA tagged Where! The alternatives we have is to write java filter list of objects by property filter that maintains the state answered expect for the Guava,... This article, we will learn Java stream filter ; java2s.com | Demo Source and support is. Exchange Inc ; user contributions licensed under CC BY-SA the Angel of the properties filtered quite elegantly to make clear! Exchange Inc ; user contributions licensed under CC BY-SA Structure table called E1IDBW1 ( special. The 2011 tsunami Thanks to the cookie consent popup returns map < A.id, list < a >. Companies have to follow a government line a Java collection ( based on 2 keys cookie popup. 'S either PriceType.SELLING or PriceType.BUYING licensed under CC BY-SA a function that takes in two arrays. Demo Source and support | Demo Source and support I convert a String representation required! Partition answer by Tagir Valeev inspired me to use custom Collector which returns