Suppose you have a comma-separated list of String e.g. "Samsung, Apple, Sony, Google, Microsoft, Amazon" and you want to convert it into an ArrayList containing all String elements e.g. Samsung, Apple, Google, etc. How do you do that? Well, Java doesn't provide any such constructor or factory method to create ArrayList from delimited String, but you can use String.split() method and Arrays.asList() method together to create an ArrayList from any delimited String, not just comma separated one.
Learn Java and Programming through articles, code examples, and tutorials for developers of all levels.
How to create and initialize List or ArrayList in one line in Java? Example
creating and initializing List at the same time
Sometimes we want to create and initialize a List like ArrayList or LinkedList in one
line much like creating an array and initializing it on the same line. If you look at The array on Java programming language you can create and initialize both primitive
and object arrays e.g. String
array very easily in just one line but in order to create a List
equivalent of that array, you need to type a lot of code. This is also one of the
tricky
Java question sometimes appears in Interview as Write Java code to create and initialize ArrayList in the same line.
How to Order and Sort Objects in Java? Comparator and Comparable Example
Java Object Sorting Example
How do you sort a list of Objects in Java is one of the frequently asked coding questions in Java interviews and surprisingly not every Java programmers know How sorting of object happens in Java. Comparator and Comparable interface along with Collections.sort() method are used to sort the list of objects in Java. compare() and compareTo() method of Comparator and Comparable interface provides comparison logic needed for sorting objects. compareTo() method is used to provide Object's natural order sorting and compare() method is used to sort Object with any arbitrary field.
Subscribe to:
Posts (Atom)