Adventures in Java – Sort an Object Array With a Collection Stream

By | September 2, 2017
QualTech Java Development Services | QualTech360Development

Stream and lambda expressions to sort an object array in just a few lines

This article is a follow up to the article Adventures in C# – Sort An Object Array With Linq and shows how to accomplish in Java the same type of object manipulation we can accomplish in C# using Linq.

In Java the collections library implement a member called stream which allows us to perform most of the same operations. You can download the Eclipse java project from here an run StreamMain.js.

In Java just like in C# the amount of code where everything happens is small and a pretty powerful feature.

public static void main(String[] args) throws IOException {

List<Menu> menuItems = null;
List<Menu> resultItems = null;

menuItems = getMenuList();

/* sorting with stream */
resultItems =,item2)->item1.getItem().compareTo(item2.getItem())).collect(Collectors.toList());

for(Menu item : resultItems) {
System.out.format(“Item %s, Price %f\n, Item Type %s”,item.getItem(), item.getPrice(), item.getItemType());

System.out.print(“Any key to end.”);;

Here as well everything is happening in the line resultItems =,item2)->item1.getItem().compareTo(item2.getItem())).collect(Collectors.toList());

The method getMenuList all it does is returning the Menu List collection we work with.

Download the code and leave us your feedback.

#QualTech360Care #QualTech360Development #QualTech360Solutions #QualTech360Java

Leave a Reply