Home  >  Core Java

Example of Collections.replaceAll in Java

By Arvind Rai, May 26, 2013
Collections.replaceAll in Java, plays the role of replacing all occurrences of any element in collection by new value. To check the equality of any element on the basis of any certain criteria, we need to override equals and hachCode.
CollectionsReplaceAll.java
package com.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CollectionsReplaceAll {
     public static void main(String[] args) {
         Bean a1 = new Bean("A");
         Bean a2 = new Bean("B");
         Bean a3 = new Bean("B");
         Bean a4 = new Bean("C");
         List<Bean> list = new ArrayList<Bean>();
         list.add(a1);
         list.add(a2);
         list.add(a3);
         list.add(a4);
         System.out.println("Before replaceAll...");
         for(Bean b: list){
             System.out.print(b.name+" ");
         }
         System.out.println("\n After replaceAll....");
         Collections.replaceAll(list, new Bean("B") , new Bean("X"));
         
         for(Bean b: list){
             System.out.print(b.name+" ");
         }
     }
}
class Bean {
    public String name;
    public Bean(String name) {
        this.name = name;
    }
    @Override
    public boolean equals(Object o) {
        return name.equals(((Bean)o).name);
    }
    @Override
    public int hashCode() {
        int hash = 13;
        hash = (31 * hash) + (null == name ? 0 : name.hashCode());
        return hash;
    }
}
Output
Before replaceAll...
A B B C 
 After replaceAll....
A X X C  
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us