2. Get the elements in common between two lists - java 8
Tools:
-JDK 8-CoderPad/Sanbox
Solution:
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
import java.util.function.Function;
class Solution
{
public static void main(String[] args)
{
//Init a
List<Integer> a = new ArrayList<Integer>();
a.add(1);
a.add(3);
a.add(4);
a.add(6);
a.add(8);
a.add(9);
//Init b
List<Integer> b= new ArrayList<Integer>();
b.add(1);
b.add(2);
b.add(3);
b.add(5);
b.add(6);
b.add(8);
List<Integer> commons = commonElements(a,b);
//Print Result
System.out.print("The elements in common between a and b are :"+ commons);
}
//method that find common elements between two lists
public static List<Integer> commonElements(List<Integer> a,List<Integer>b)
{
List<Integer> result = new ArrayList<Integer>();
//Maybe you would need to override equals and hash method for complex objects
//This method find an element of a in b
//This can be work in java 7 and less by replacing forEach to for block
a.forEach(item->
{
if(b.contains(item))
result.add(item);
});
return result;
}
}
import java.util.*;
import java.util.stream.Collectors;
import java.util.function.Function;
class Solution
{
public static void main(String[] args)
{
//Init a
List<Integer> a = new ArrayList<Integer>();
a.add(1);
a.add(3);
a.add(4);
a.add(6);
a.add(8);
a.add(9);
//Init b
List<Integer> b= new ArrayList<Integer>();
b.add(1);
b.add(2);
b.add(3);
b.add(5);
b.add(6);
b.add(8);
List<Integer> commons = commonElements(a,b);
//Print Result
System.out.print("The elements in common between a and b are :"+ commons);
}
//method that find common elements between two lists
public static List<Integer> commonElements(List<Integer> a,List<Integer>b)
{
List<Integer> result = new ArrayList<Integer>();
//Maybe you would need to override equals and hash method for complex objects
//This method find an element of a in b
//This can be work in java 7 and less by replacing forEach to for block
a.forEach(item->
{
if(b.contains(item))
result.add(item);
});
return result;
}
}
No hay comentarios:
Publicar un comentario