How to sort javascript array with objects?


var people = [
    {Name: "Jack Lee", Age: 21},
    {Name: "Jack Ma", Age:31},
    {Name: "Steve Liu", Age: 12},
    {Name: "Alice  Xu", Age: 42}
];


//Sort by name
people.sort(function(a,b){
   return   (a.Name.toLowerCase() > b.Name.toLowerCase()) ? 1 : -1;
});

//Sort by ES6 arrow function
people.sort((a,b)=>{
   return   (a.Name.toLowerCase() > b.Name.toLowerCase()) ? 1 : -1;
});

Sorted array by name:
>people
 
0: {Name: "Alice  Xu", Age: 42}
1: {Name: "Jack Lee", Age: 21}
2: {Name: "Jack Ma", Age: 31}
3: {Name: "Steve Liu", Age: 12} 


//sort by age
 people.sort(function(a,b){
   return   (a.Age > b.Age)? 1 : -1;
});


//Sort by ES6 arrow function
 people.sort((a,b)=>{
   return   (a.Age > b.Age)? 1 : -1;
});

Sorted array by age:
>people

0: {Name: "Steve Liu", Age: 12}
1: {Name: "Jack Lee", Age: 21}
2: {Name: "Jack Ma", Age: 31}
3: {Name: "Alice  Xu", Age: 42} 

Read More

Use java lombok in POJO.

You need to add lombok dependency into your pom file:

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.18</version>
    <scope>provided</scope>
</dependency>

and you need to install lombok ito your IDE with this command:
java -jar lombok-1.16.18.jar

The @Data annotation will give you everything including getter/Setter/ hashcode /equals and toString methods.


import lombok.Data;

@Data
public class Person {
	private Integer age;
	private String name;
}

Read More

Java Stream Reduce examples:

import java.util.Arrays;
import java.util.List;

public class JavaStreamReducer {

	public static void main(String[] args) {

		// Reduce Array to String.
		String[] people = { "Jack", "Steve", "Alice" };
		Arrays.stream(people).reduce((x, y) -> x + " | " + y).ifPresent(s -> System.out.println(s));
		// Reduce List to String.

		System.out.println("\n");
		List<String> peoplelist = Arrays.asList(people);
		peoplelist.stream().reduce((x, y) -> x + "," + y).ifPresent(s -> System.out.println(s));
		System.out.println("\n");

		// function programming with Stream
		String greeting = greet(peoplelist);
		System.out.println(greeting + "\n");

		Integer[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
		int sum = Arrays.stream(numbers).reduce(0, (x, y) -> x + y);
                //	 or with .reduce(0, Integer::sum);
		System.out.println("Sum of Array: " + sum);
		System.out.println("\n");
		// Reduce List to sum.
		List<Integer> list = Arrays.asList(numbers);
		sum = list.stream().reduce(0, (x, y) -> x + y);
		System.out.println("Sum of List: " + sum);

		List<Integer> list2 = Arrays.asList(2, 3, 4);
		// Here result will be 2*2 + 2*3 + 2*4 that is 18.
		int res = list2.parallelStream().reduce(2, (s1, s2) -> s1 * s2, (p, q) -> p + q);
		System.out.println(res);
	}

	public static String greet(List<String> names) {
		String greeting = names.stream().map(name -> name + " ").reduce("Welcome ", (acc, name) -> acc + name);
		return greeting + "!";
	}

output:
Jack | Steve | Alice


Jack,Steve,Alice


Welcome Jack Steve Alice !

Sum of Array: 55


Sum of List: 55
18

 

Read More

How to filter a map with Java Stream?


class Person {
	private Integer age;
	private String name;
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Person(Integer age, String name) {
		super();
		this.age = age;
		this.name = name;
	}
	@Override
	public String toString() {
		return "Person [age=" + age + ", name=" + name + "]";
	}

}


import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class JavaStreamMapFilter {

	public static void main(String[] args) {

		
		//Example of stream filter return  String
		Map<String, String> nameMap  = new HashMap<>();
		nameMap.put("JL", "Jack Lee");
		nameMap.put("JM", "Jack Ma");
		nameMap.put("SL", "Steve Liu");
		nameMap.put("AX", "Alice Xu");
 
        String result = nameMap.entrySet().stream()
                .filter(map -> "Jack Ma".equals(map.getValue()))
                .map(map -> map.getValue())
                .collect(Collectors.joining());

        System.out.println("\n\nResult : " + result);
		
		//Example of stream filter return  a Map
        Map<String, Person>   peopleMap = getMap();
		System.out.println("Initial  map :  ");
		peopleMap.forEach((k, v) -> System.out.println(k + ":" + v));
		Map<String, Person> oldPeopleMap = peopleMap.entrySet().stream().filter(p -> p.getValue().getAge() > 30)
				.collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));

		System.out.println("\n\nAfter filtering, here is the map :  ");
		oldPeopleMap.forEach((k, v) -> System.out.println(k + ":" + v));
	}

	private static Map<String, Person> getMap() {
		Map<String, Person> peopleMap = new HashMap<>();
		Person person1 = new Person(21, "Jack Lee");
		peopleMap.put("JL", person1);
		Person person2 = new Person(31, "Jack Ma");
		peopleMap.put("JM", person2);
		Person person3 = new Person(12, "Steve Liu");
		peopleMap.put("SL", person3);
		Person person4 = new Person(42, "Alice XU");
		peopleMap.put("AX", person4);

		return peopleMap;
	}

}



Here the output:

Result : Jack Ma
Initial  map :  
JL:Person [age=21, name=Jack Lee]
JM:Person [age=31, name=Jack Ma]
AX:Person [age=42, name=Alice XU]
SL:Person [age=12, name=Steve Liu]


After filtering, here is the map :  
JM:Person [age=31, name=Jack Ma]
AX:Person [age=42, name=Alice XU]

Read More

How to filter a List with Java Stream?

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


class Person {
	private Integer age;
	private String name;
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Person(Integer age, String name) {
		super();
		this.age = age;
		this.name = name;
	}
	@Override
	public String toString() {
		return "Person [age=" + age + ", name=" + name + "]";
	}

}

public class JavaStreamFilter {

	public static void main(String[] args) {

		List<Person> people = getArrayList();
		List<Person> oldPeople = people.stream().filter(p -> p.getAge() > 30).collect(Collectors.toList());
		System.out.println("\nThe sorted list:");
		displayList(oldPeople);
	}

	private static void displayList(List<Person> people) {

		for (Person p : people) {
			System.out.println(p);
		}
	}

	private static List<Person> getArrayList() {
		List<Person> people = new ArrayList<Person>();
		Person person1 = new Person(21, "Jack Lee");
		people.add(person1);
		Person person2 = new Person(31, "Jack Ma");
		people.add(person2);
		Person person3 = new Person(12, "Steve Liu");
		people.add(person3);
		Person person4 = new Person(42, "Alice XU");
		people.add(person4);

		return people;
	}




The result is: 
The sorted list:
Person [age=31, name=Jack Ma]
Person [age=42, name=Alice XU]

Read More

Add copyright statement in all source files.

You have completed you development for a large project and QA finished the tests as well, everything works perfectly,so you may decide to celebrate a little bit. Before you come out a great plan, your manager come over and told you there is some tedious thing to do: You need to add a copyright statement to each and every source code file. Jus like many people, you may start quickly estimating how many files you need to CTRL+C and CTRL+V, and then do a integration test before you can commit your change.If you are a hard-working employee, you may your change right way, but if you are a ‘lazy’ programmer, you may try something differently:

As you are a programmer, you are good at coding, why not write a program to do the job, here is the jave code:

Step 1: Find out all the files need to be updated.


import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class ListFilesUtil {
	public List <String> listFilesUnderDirectories(String directoryName) {
		List<String> fileList = new ArrayList<>();
		File directory = new File(directoryName);
		File[] fList = directory.listFiles();
		for (File file : fList) {
			if (file.isFile() && file.getAbsolutePath().endsWith(".js")) {
				fileList.add(file.getAbsolutePath()); 
			} else if (file.isDirectory()) {
				fileList.addAll(listFilesUnderDirectories(file.getAbsolutePath()));
			}
		}
		return fileList;
	}
}

Step2: For each file, re-write it with the copy right content


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

public class RewriteFile {

	public static void main(String[] args) {
		
		String targetDirectory = "target_directory"; 
		RewriteFile rf = new RewriteFile();
		String licence =  rf.readFile("copyright.txt") ;
		ListFilesUtil util = new ListFilesUtil(); 
		List <String> fileList = util.listFilesUnderDirectories(targetDirectory);
		
		fileList.forEach(file->{
			 rf.rewriteFile(file, licence);
		});
	}

	public void rewriteFile(String fileName, String licence) {

		try {
			
			StringBuffer sb = new StringBuffer();
			try {
				FileReader fr = new FileReader(fileName);
				BufferedReader br = new BufferedReader(fr);
				String line = "";
				
				line = br.readLine();
				while (line != null) {
					sb.append(line+"\n");
					line = br.readLine();
				}
				br.close();
			} catch (FileNotFoundException e) {
				System.out.println("File was not found!");
			} catch (IOException e) {
				System.out.println("No file found!");
			}
			String newContext = licence + "\n"+  sb.toString();
			
			FileWriter fw = new FileWriter(fileName, false);
			BufferedWriter bw = new BufferedWriter(fw);
			bw.write(newContext);
		 
			bw.close();
		} catch (FileNotFoundException e) {
			System.out.println("Error1!");
		} catch (IOException e) {
			System.out.println("Error2!");
		}
	}

	public String readFile(String fileName) {

		StringBuffer sb = new StringBuffer();
		try {
			FileReader fr = new FileReader(fileName);
			BufferedReader br = new BufferedReader(fr);
			String line = "";

			while ((line = br.readLine()) != null) {
				sb.append(line +"\n");
			}
			br.close();
		} catch (FileNotFoundException e) {
			System.out.println("File was not found!");
		} catch (IOException e) {
			System.out.println("No file found!");
		}
		return sb.toString();
	}
}

Read More

How to create a user for Mongdb?

To create a user in mongdb, you need to open a terminal, assuming mongod service is running, ,

    (This command will do the job:   brew services start mongodb)

   >mongo
   >use testdb

  db.createUser(
  {
    user: "testUser",
    pwd: "12345678",
    roles: [
       { role: "read", db: "reporting" },
       { role: "read", db: "products" },
       { role: "read", db: "sales" },
       { role: "readWrite", db: "accounts" }
    ]
  }
)



</pre>
<div class="line number4 index3 alt1"><code class="plain plain">db.createUser(</code></div>
<div class="line number5 index4 alt2"><code class="plain spaces">  </code><code class="plain plain">{</code></div>
<div class="line number6 index5 alt1"><code class="plain spaces">    </code><code class="plain plain">user: "root",</code></div>
<div class="line number7 index6 alt2"><code class="plain spaces">    </code><code class="plain plain">pwd: "DanielSecret2022",</code></div>
<div class="line number8 index7 alt1"><code class="plain spaces">    </code><code class="plain plain">roles: [</code></div>
<div class="line number9 index8 alt2"><code class="plain spaces"></code> <code class="plain plain"></code></div>
<div class="line number11 index10 alt2"><code class="plain spaces">       </code><code class="plain plain">{ role: "read", db: "RNAseqAnalysis" },</code></div>
<div class="line number12 index11 alt1"><code class="plain spaces">       </code><code class="plain plain">{ role: "readWrite", db: "RNAseqAnalysis" }</code></div>
<div class="line number13 index12 alt2"><code class="plain spaces">    </code><code class="plain plain">]</code></div>
<div class="line number14 index13 alt1"><code class="plain spaces">  </code><code class="plain plain">}</code></div>
<div class="line number15 index14 alt2"><code class="plain plain">)</code></div>
<div class="line number15 index14 alt2"></div>
<div class="line number15 index14 alt2"></div>
<pre>

Try to connect to it in you code with mongodb://testUser:12345678@yourhost:port/testdb

Enjoy!

Read More

How to sort a List with Java Lambda

want to sort a list in java with Lambda? Here is how:

 
class Person {
	private Integer age;
	private String name;

	public Integer getAge() {
		return age;
	}

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Person(Integer age, String name) {
		super();
		this.age = age;
		this.name = name;
	}

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

 
package com.leespace.java8;

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

public class JavaLambdaSort {

	public static void main(String[] args) {

		 List <Person> people= getArrayList();
		 
		 //Sort by name  in traditional way with Comparator:
		 Collections.sort(people, new Comparator <Person> () {

			@Override
			public int compare(Person p1, Person p2) {
				return p1.getName().compareTo(p2.getName());
			}
		 });
		 displayList(people);
		 
		 //Sort by name  in traditional way with Comparator:
		 Collections.sort(people, new Comparator <Person> () {

			@Override
			public int compare(Person p1, Person p2) {
				return p1.getAge().compareTo(p2.getAge());
			}
		 });
		 displayList(people);
		 
		 //Sort by name  in with lambda:
		 Collections.sort(people, (p1,p2) -> p1.getName().compareTo(p2.getName()));
		 displayList(people);
		 
		 //Sort by age  in with lambda:
		 Collections.sort(people, (p1,p2) -> p1.getAge().compareTo(p2.getAge()));
		 displayList(people);
		 
	}

	private static void displayList(List<Person> people) {
		System.out.println("\nThe sorted list:");
		for (Person p:people) {
			 System.out.println(p);
		 }
	}

	private static List<Person>   getArrayList() {
		List<Person> people = new ArrayList<Person>();
		Person person1 = new Person(21, "Jack Lee");
		people.add(person1);
		Person person2 = new Person(31, "Jack Ma");
		people.add(person2);
		Person person3 = new Person(12, "Steve Liu");
		people.add(person3);
		Person person4 = new Person(42, "Alice XU");
		people.add(person4);
		
		return people;
	}

}


Read More