Return a default value from a Map in Java 8

Consider the following Employee class:

public class Employee
{
    private UUID id;
    private String name;
    private int age;

    public Employee(UUID id, String name, int age)
    {
        this.id = id;
        this.name = name;
        this.age = age;
    }
        
    public UUID getId()
    {
        return id;
    }

    public void setId(UUID id)
    {
        this.id = id;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }    
    
    public int getAge()
    {
        return age;
    }

    public void setAge(int age)
    {
        this.age = age;
    }
}

Let’s put some Employee objects into a hash map:

Read more of this post

Creating sorted sets with C# .NET

The SortedSet of T object is the sorted version of the HashSet object. We’ve already seen what a HashSet can do for you in the referenced post. A SortedSet keeps the elements in increasing order.

Consider the following integer set:

SortedSet<int> sortedInts = new SortedSet<int>();
sortedInts.Add(1);
sortedInts.Add(4);
sortedInts.Add(3);
sortedInts.Add(1);
sortedInts.Add(3);
sortedInts.Add(10);
sortedInts.Add(8);
sortedInts.Add(3);
sortedInts.Add(1);
sortedInts.Add(4);
foreach (int i in sortedInts)
{
	Debug.WriteLine(i);
}

This will print…

1
3
4
8
10

Notice that duplicates were rejected to ensure uniqueness just like in the case of HashSets.

That is straightforward for primitive types like integers since .NET “knows” how to compare them. It can decide whether 10 is greater than 5, we don’t need to provide any help.

However what about reference types like your own objects, such as this one?

public class Band
{
	public string Name { get; set; }
	public int YearFormed { get; set; }
	public int NumberOfMembers { get; set; }
	public int NumberOfRecords { get; set; }
}

How can .NET decide on the ordering of your objects? We’ll need to give it a hint by providing an object which implements the generic IComparer of T interface like we saw in this post. We’ll let the Band objects be sorted by their names:

public class BandNameComparer : IComparer<Band>
{
	public int Compare(Band x, Band y)
	{
		return x.Name.CompareTo(y.Name);
	}
}

Let’s see this in action:

SortedSet<Band> bands = new SortedSet<Band>(new BandNameComparer());
bands.Add(new Band() { YearFormed = 1979, Name = "Great band", NumberOfMembers = 4, NumberOfRecords = 10 });
bands.Add(new Band() { YearFormed = 1985, Name = "Best band", NumberOfMembers = 5, NumberOfRecords = 15 });
bands.Add(new Band() { YearFormed = 1985, Name = "Well known band", NumberOfMembers = 5, NumberOfRecords = 15 });
bands.Add(new Band() { YearFormed = 1979, Name = "Famous band", NumberOfMembers = 4, NumberOfRecords = 10 });
bands.Add(new Band() { YearFormed = 1979, Name = "Great band", NumberOfMembers = 4, NumberOfRecords = 10 });
bands.Add(new Band() { YearFormed = 1985, Name = "Best band", NumberOfMembers = 5, NumberOfRecords = 15 });
bands.Add(new Band() { YearFormed = 1985, Name = "Best band", NumberOfMembers = 5, NumberOfRecords = 15 });
bands.Add(new Band() { YearFormed = 1979, Name = "Great band", NumberOfMembers = 4, NumberOfRecords = 10 });
bands.Add(new Band() { YearFormed = 1979, Name = "Famous band", NumberOfMembers = 4, NumberOfRecords = 10 });

foreach (Band band in bands)
{
	Debug.WriteLine(band.Name);
}

This will print…

Best band
Famous band
Great band
Well known band

…so not only were the items sorted by their names but the non-unique values were rejected as well. The IComparer argument also provided a way to declare equality.

View all various C# language feature related posts here.

Using the KeyedCollection object in C# .NET

The abstract generic KeyedCollection object can be used to declare which field of your custom object to use as a key in a Dictionary. It provides sort of a short-cut where you’d want to organise your objects in a Dictionary by an attribute of that object.

Let’s take the following object as an example:

public class CloudServer
{
	public string CloudProvider { get; set; }
	public string ImageId { get; set; }
	public string Size { get; set; }
}

The Image IDs are always unique so the ImageId property seems to be a good candidate for a dictionary key.

Here’s an example:

Read more of this post

Using the HashSet of T object in C# .NET to store unique elements

The generic HashSet of T is at first sight a not very “sexy” collection. It simply stores objects with no order, index or key to look up individual elements.

Here’s a simple HashSet with integers:

HashSet<int> intHashSet = new HashSet<int>();
intHashSet.Add(1);
intHashSet.Add(3);
intHashSet.Add(5);
intHashSet.Add(2);
intHashSet.Add(10);

HashSets can be handy when you want to guarantee uniqueness. The following example will only put the unique integers in the set:

Read more of this post

Introduction to generics in C# Part 6

Introduction

In the previous post we looked at constraints on generic type parameters using the ‘where’ keyword. We looked at an example where we wanted to limit the usage of an interface, IPropertiesPrinter, to those objects that implement another interface, namely IPrintable. We wanted to make sure that the generic type, i.e. the object to be printed, will have the GetProperties() method available. Without the constraint the generic object would only have the methods inherited from the Object class, such as ToString and GetHashCode.

In this post we’ll look at an example where not even constraints seem to provide a solution. I wanted to include this example in this series to show that sometimes not even generics can help create generic code.

Read more of this post

Introduction to generics in C# Part 5

Introduction

In the previous post we looked at how to declare multiple type parameters. We saw that it was a very simple thing to do. We just add as many parameters as we need and separate them by a comma. It’s perfectly fine to refer to those parameters later on in the class level functions. It’s equally fine to put multiple parameters on the function level as well if you don’t want to make the entire class generic.

In this post we’ll take a quick look at parameter type constraints.

Read more of this post

Introduction to generics in C# Part 4

Introduction

In the previous post we saw how to build generic functions. It’s not necessary to make an entire class generic if we want to keep the functions independent of any class level type parameters. We saw an example, a configuration settings reader, where it was unnecessary to declare the return type on the class level. That would put a constraint on the usage of a single configuration reader instance. Instead, we let the caller define the return type on the ReadConfigurationValue function which makes the configuration reader class more flexible.

In this post we’ll look at declaring multiple generic parameters.

Read more of this post

Introduction to generics in C# Part 3

Introduction

In the previous post on generics we looked at an example of reading application settings from a configuration file. Application settings come in key-value pairs where the value can be of different type: string, integer, boolean and various others. The generic ConfigurationReaderService helped us improve the non-generic code where the function caller had to take care of the type conversion and validation steps.

In this post we’ll further improve our code by looking into generic methods.

Read more of this post

Introduction to generics in C# Part 2

Introduction

In the previous post we started looking into generics in .NET. We also saw an initial example where an abstract base class had a type parameter to define the type of the Id property. The implementing classes could then all derive from this generic class and define their Id type along the way.

In this post we’ll look at another example where generics can be useful.

Read more of this post

Introduction to generics in C# Part 1

Introduction

Generics is a way to generalise your code in .NET. We can generalise the types that an object and/or a function operates on. With generics we can reuse the same portion of code with multiple types. If used in appropriate places it can be a great tool against code duplication.

Generics is nothing new, it was a new language feature in .NET 2.0.

Read more of this post

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: