JAVA Collection - Using HashMap With BiFunction In Java NetBeans
Source Code:
package javaapp;
import java.util.HashMap;
// create a class to use it with the hashmap
class User{
private int id;
private String name;
public User(){}
public User(int _id,String _name){
this.id = _id;
this.name =_name;
}
public int getId(){
return this.id;
}
public String getName(){
return this.name;
}
public void setId(int id){
this.id = id;
}
public void setName(String name){
this.name = name;
}
public String ToString(){
return "ID = "+id+" NAME = "+name ;
}
}
public class Woirk {
public static void main(String[] args){
HashMap<Integer,User> userList = new HashMap<Integer,User>();
userList.put(10, new User(1,"omar"));
userList.put(21, new User(2,"bilal"));
userList.put(32, new User(3,"kamal"));
userList.put(43, new User(4,"rachid"));
userList.put(54, new User(5,"rami"));
userList.put(65, new User(6,"karim"));
printAllData(userList);
User u1 = userList.get(54);
User u2 = new User(600, "TheNewUser");
BiFunction<User, User,Boolean> bi = (x, y) -> {
Boolean state = false;
for(Integer i : userList.keySet()){
if(userList.get(i).equals(x)){
userList.replace(i, y);
state = true;
break;
}
}
return state;
};
System.out.println(bi.apply(u1, u2));
System.out.println("---------------------");
printAllData(userList);
}
// cretate a function to print data from the hashmap
public static void printAllData(HashMap<Integer,User> list){
for(Integer i : list.keySet())
{
System.out.println(list.get(i).ToString());
}
System.out.println("----------------------");
}
}
//OUTPUT:
ID = 3 NAME = kamal
ID = 6 NAME = karim
ID = 2 NAME = bilal
ID = 5 NAME = rami
ID = 1 NAME = omar
ID = 4 NAME = rachid
----------------------
true
---------------------
ID = 3 NAME = kamal
ID = 6 NAME = karim
ID = 2 NAME = bilal
ID = 600 NAME = TheNewUser
ID = 1 NAME = omar
ID = 4 NAME = rachid
----------------------
Bagikan
Java - How To Use HashMap With BiFunction In Java
4/
5
Oleh
insurance