0% found this document useful (0 votes)
33 views9 pages

SkillWeek6 32536

Uploaded by

g98pfyb97m
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views9 pages

SkillWeek6 32536

Uploaded by

g98pfyb97m
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Week 6.

Collection Framework Java Generics, Stack, PriorityQueue & Comparator


1) Given a string s, regroup the characters of s so that any two adjacent characters are not
the same. Return any possible rearrangement of s or return "" if not possible. Details: a)
Input: A string s consisting of lowercase English letters. The length of s is between 1 and
500 characters. b) Output: A string where no two adjacent characters are identical. If
such a rearrangement is not possible, return an empty string. Example: a) Input: s =
"aab" Output: "aba" (or any other valid rearrangement like "baa") b) Input: s = "aaab"
Output: "" (since it's not possible to rearrange the characters without having at least two
adjacent as) Constraints: a) The string length is between 1 and 500 characters. b) The
string consists only of lowercase English letters. Approach: Character Frequency with
LinkedList: Use a LinkedList to store characters and their frequencies, ensuring you can
maintain and update frequencies as needed. PriorityQueue (Min-Heap): Use the
PriorityQueue with a custom comparator to manage the characters based on their
frequencies. Stack for Previous Characters: Use a Stack to track previously placed
characters to avoid placing the same character consecutively.
Code:
package SkillWeek6;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

public class exp1 {


public String reorganizeString(String s) {

Map<Character, Integer> frequencyMap = new HashMap<>();


for (char c : s.toCharArray()) {
frequencyMap.put(c, frequencyMap.getOrDefault(c, 0) + 1);
}

PriorityQueue<Map.Entry<Character, Integer>> maxHeap = new PriorityQueue<>(


(a, b) -> b.getValue() - a.getValue());
maxHeap.addAll(frequencyMap.entrySet());

StringBuilder result = new StringBuilder();


Map.Entry<Character, Integer> prev = null;

while (!maxHeap.isEmpty()) {
Map.Entry<Character, Integer> current = maxHeap.poll();
result.append(current.getKey());

current.setValue(current.getValue() - 1);

if (prev != null && prev.getValue() > 0) {


maxHeap.offer(prev);
}

prev = current;
}

if (result.length() != s.length()) {
return "";
}

return result.toString();
}

public static void main(String[] args) {


exp1 z = new exp1();

String s1 = "aab";
String s2 = "aaab";

System.out.println(z.reorganizeString(s1));
System.out.println(z.reorganizeString(s2));

}
}
2) Advanced Type Bounds with Generics

Objective: Create a generic class that uses advanced type bounds and wildcards and
understand how the generic methods work with type bounds and wildcards. Details:
Class Definition: a) Define T with multiple bounds: it must implement both Comparable.
Methods: a) processList(List list): This method should process a list of elements that are
of type T or its subtypes. It should iterate through the list and print each element. b)
addToList(List list, T element): This method should add an element of type T to a list that
can hold T or any supertype of T. Use Case: a) Create a Product class that implements
Comparable and Serializable. b) Use AdvancedGeneric with Product to:  Process a list of
Product objects.  Add a new Product to another list and process it.
Code:

package SkillWeek6;
import java.io.Serializable;
import java.util.*;
class Product implements Comparable<Product>, Serializable {
private String name;
private double price;

public Product(String name, double price) {


this.name = name;
this.price = price;
}

public String getName() {


return name;
}

public double getPrice() {


return price;
}

public int compareTo(Product other) {


return Double.compare(this.price, other.price);
}

public String toString() {


return "Product{name='" + name + "', price=" + price + "}";
}
}

class AdvancedGeneric<T extends Comparable<T> & Serializable> {

public void processList(List<? extends T> list) {


for (T element : list) {
System.out.println(element);
}
}

public void addToList(List<? super T> list, T element) {


list.add(element);
}
}

public class exp2 {


public static void main(String[] args) {

List<Product> productList = Arrays.asList(


new Product("Laptop", 999.99),
new Product("Phone", 699.99),
new Product("Tablet", 399.99)
);

AdvancedGeneric<Product> advancedGeneric = new AdvancedGeneric<>();

System.out.println("Processing product list:");


advancedGeneric.processList(productList);

List<Product> anotherList = new ArrayList<>();

Product newProduct = new Product("Smartwatch", 199.99);


advancedGeneric.addToList(anotherList, newProduct);

System.out.println("\nProcessing another product list after adding a new product:");


advancedGeneric.processList(anotherList);
}
}
3) A class Employee that has the following requirements:
Objective: To Understand the functionality of a custom Comparator for sorting
Employee objects by multiple criteria and to ensure correct application of the complex
sorting logic.
Class Definition:
a) The Employee class has the following attributes: name: String, age: Integer, Salary:
Double.
b) Implement the Comparable interface in the Employee class to provide a natural
ordering based on salary.
Custom Comparator Implementation:
a) Implement a custom Comparator that provides the following functionalities:
Primary Sorting: Sort employees by age in ascending order.
Secondary Sorting: If two employees have the same age, sort them by salary in
descending order.
Tertiary Sorting: If two employees have the same age and salary, sort them by name
in alphabetical order

Code:

package SkillWeek6;
import java.util.*;
class Employee implements Comparable<Employee> {
private String name;
private Integer age;
private Double salary;

public Employee(String name, Integer age, Double salary) {


this.name = name;
this.age = age;
this.salary = salary;
}

public String getName() {


return name;
}

public Integer getAge() {


return age;
}

public Double getSalary() {


return salary;
}

public int compareTo(Employee other) {

return this.salary.compareTo(other.salary);
}

public String toString() {


return "Employee{name='" + name + "', age=" + age + ", salary=" + salary + "}";
}
}

class EmployeeComparator implements Comparator<Employee> {

public int compare(Employee e1, Employee e2) {


int ageComparison = e1.getAge().compareTo(e2.getAge());
if (ageComparison != 0) {
return ageComparison;
}

int salaryComparison = e2.getSalary().compareTo(e1.getSalary());


if (salaryComparison != 0) {
return salaryComparison;
}

return e1.getName().compareTo(e2.getName());
}
}

public class exp3 {


public static void main(String[] args) {

List<Employee> employees = Arrays.asList(


new Employee("Alice", 30, 50000.0),
new Employee("Bob", 25, 70000.0),
new Employee("Charlie", 30, 60000.0),
new Employee("David", 30, 50000.0),
new Employee("Eve", 25, 70000.0)
);

Collections.sort(employees, new EmployeeComparator());

System.out.println("Sorted list of employees:");


for (Employee e : employees) {
System.out.println(e);
}
}
}

You might also like