Java Float to String Example

Published / by ak / Leave a Comment

Converting Float to String in java is very easy and it is very frequently used.

1) Float class provide a static method toString() , which will convert float to string.(see below example)

2)We can also use String class static method valueOf() , which will return String representation of any object (in our case Float).

But Sometime we need to restrict number of decimal places ,In that case String class provide a static method format which Returns a formatted string using the specified format string and arguments.(see below example)

Example:

public class JavaFloatToStringExample {

	public static void main(String[] args) {

		Float f = new Float(3.14234);

		// Internally Float toString method  also call Float.toString(value);
		String floatStringValue = Float.toString(f);
		System.out.println("Float String value using toString :: " + floatStringValue);

		// There is also another way using String static method value of
		floatStringValue = String.valueOf(f);
		System.out.println("Float to string using String valueof  ::" + floatStringValue);

		// If we want to control the number of decimal places to be restricted , we
		// can use String class format method
		floatStringValue = String.format("%.1f", f);
		System.out.println("Float to string with one decimal place ::" + floatStringValue);

		floatStringValue = String.format("%.2f", f);
		System.out.println("Float to string with two decimal place::" + floatStringValue);

	}

}

Result :

Float String value using toString :: 3.14234
Float to string using String valueof  ::3.14234
Float to string with one decimal place ::3.1
Float to string with two decimal place::3.14

convert list to map in java 8 ( using lambda)

Published / by ak / Leave a Comment

Student.java

public class Student {

	private String id;

	private String name;

	private int marks;

	public Student(String id, String name, int marks) {
		this.id = id;
		this.name = name;
		this.marks = marks;
	}

	//Please set getter and setter
}

LambdaListToMapExample.java


import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class LambdaListToMapExample {

	public static void main(String[] args) {

		List <Student> students = new ArrayList<>();

		Student s1 = new Student("id1", "Alex", 80);
		Student s2 = new Student("id2", "Ram", 30);
		Student s3 = new Student("id3", "Chong", 23);
		Student s4 = new Student("id4", "Dlex", 85);
		Student s5 = new Student("id5", "Mary", 90);

		students.add(s1);
		students.add(s2);
		students.add(s3);
		students.add(s4);
		students.add(s5);

		System.out.println("Students List :: " + students);

		
                Map<String, Student> idToStudentMap= students.stream().
collect(Collectors.toMap(Student::getId, Function.identity()));
		
		System.out.println("result ::"+idToStudentMap);

	}

}


Result:
Students ::
 [Student [id=id1, name=Alex, marks=80],
 Student [id=id2, name=Ram, marks=30],
 Student [id=id3, name=Chong, marks=23],
 Student [id=id4, name=Dlex, marks=85], 
 Student [id=id5, name=Mary, marks=90]]

result::
{id2=Student [id=id2, name=Ram, marks=30],
 id1=Student [id=id1, name=Alex, marks=80],
 id4=Student [id=id4, name=Dlex, marks=85], 
id3=Student [id=id3, name=Chong, marks=23],
 id5=Student [id=id5, name=Mary, marks=90]}

Java Comparable and Comparator example

Published / by ak / 6 Comments on Java Comparable and Comparator example

 

Java list are sorted as :
Collections.sort(l);//l is list

if List consist of String it is sorted on alphabetical order and if it is list of date then is sorted into chronological order.

But if need to sort a object (e.g Person object which consist of three field .firstName, secondName, age) . if we try to sort the objects
using Collections.sort(l); It will throw an exception. Please check below example.

public class Person {

private String firstName;

private String lastName;

private int age;

public Person(String firstName , String lastName , int age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}

//Please set setter and getter

}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class JavaComparatorTest {

	public static void main(String[] args) {
                Person p1 =  new Person("Roger","lek",40);
		Person p2 =  new Person("Carl","lewis",20);
		Person p3 =  new Person("Luis","jeans",50);
		Person p4 =  new Person("Jack","Blacke",10);
		
		List personList = new ArrayList<>();
		personList.add(p1);
		personList.add(p2);
		personList.add(p3);
		personList.add(p4);
		
		Collections.sort(personList);
		
		for(Person person:personList){
			System.out.println("Person :: "+person.toString());
			
		}
}

}

Result

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	The method sort(List) in the type Collections is not applicable for the arguments (List)

	at test.blog.sort.JavaComparatorTest.main(JavaComparatorTest.java:23)

 

As you saw in above example. An exception is thrown if try to sort an object using Collection.sort().

Java has provide solution to above problem using two interface Comparator and Comparable.

Comparator and Comparable are two inteface provided by java . Both of them used for ordering on some collection of objects.

Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don’t have a natural ordering.

Comparable imposes a total ordering on the objects of each class that implements it. This ordering based on class’s natural ordering.
e.g, Integer and Date class implement Comparable interface. i.e. why you can sort directly a list of Integer and Date .

Example:

public class Person implements Comparable{
	
	private String firstName;
	
	private String lastName;
	
	private int age;
	
	public Person(String firstName , String lastName , int age) {
		this.firstName = firstName;
		this.lastName = lastName;
		this.age = age;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public int getAge() {
		return age;
	}

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

	@Override
	public String toString() {
		return "Person [firstName=" + firstName + ", lastName=" + lastName + ", age=" + age + "]";
	}

	@Override
	public int compareTo(Person p) {
		// TODO Auto-generated method stub
		return this.age - p.age;
	}
	
}

Comparable Example:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class JavaCompareableTest {

	public static void main(String[] args) {
		
		
		Person p1 =  new Person("Roger","lek",40);
		Person p2 =  new Person("Carl","lewis",20);
		Person p3 =  new Person("Luis","jeans",50);
		Person p4 =  new Person("Jack","Blacke",10);
		
		List <Person> personList = new ArrayList<>(); 
                personList.add(p1); 
                personList.add(p2);
                personList.add(p3);
                personList.add(p4); 

                Collections.sort(personList); 

                for(Person person:personList){
                      System.out.println("First Name :: " + person.getFirstName() + " Last Name :: " + person.getLastName() + " Age ::" + person.getAge()); 

        } 

} 

}

Comparator Example:

import java.util.Comparator;

public class SortByPersonLastName implements Comparator{

	@Override
	public int compare(Person o1, Person o2) {
		// TODO Auto-generated method stub
		return o1.getLastName().compareTo(o2.getLastName());
	}


}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class JavaComparatorTest {

	public static void main(String[] args) {
		
		
		Person p1 =  new Person("Roger","lek",40);
		Person p2 =  new Person("Carl","lewis",20);
		Person p3 =  new Person("Luis","jeans",50);
		Person p4 =  new Person("Jack","Blacke",10);
		
		List personList = new ArrayList<>();
		personList.add(p1);
		personList.add(p2);
		personList.add(p3);
		personList.add(p4);
		
		Collections.sort(personList,new SortByPersonLastName());
		
		for(Person person:personList){
			System.out.println("Person :: "+person.toString());
			
		}

	}

}