Java Stream Example :
Convert List into Set
package
conversionlist;
public
class Product {
int
pid;
String pname;
float
pprice;
public
int getPid() {
return pid;
}
public
void setPid(int pid) {
this.pid = pid;
}
public
String getPname() {
return pname;
}
public
void setPname(String pname) {
this.pname
= pname;
}
public
float getPprice() {
return pprice;
}
public
void setPprice(float pprice)
{
this.pprice
= pprice;
}
}
package conversionlist;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class ProductMain {
public static void main(String[] args) {
List<Product> l=new
ArrayList<>();
Product p1=new Product();
p1.setPid(101);
p1.setPname("mobile");
p1.setPprice(10000.00f);
Product p2=new Product();
p2.setPid(102);
p2.setPname("laptop");
p2.setPprice(45000.00f);
Product p3=new Product();
p3.setPid(103);
p3.setPname("tv");
p3.setPprice(17000.00f);
Product p4=new Product();
p4.setPid(104);
p4.setPname("fridge");
p4.setPprice(19000.00f);
Product p5=new Product();
p5.setPid(105);
p5.setPname("thinkpad");
p5.setPprice(17000.00f);
l.add(p1);
l.add(p2);
l.add(p3);
l.add(p4);
l.add(p5);
// Converting product List into Set
Set<Float> price=l.stream()
.filter(p->p.getPprice()<20000.00f)
.map(p->p.getPprice())
.collect(Collectors.toSet());// collect it as Set(remove duplicate elements)
System.out.println(price);
}
}
o/p:--------------------------
[17000.0,
19000.0, 10000.0]
No comments:
Post a Comment