Priority Queue introduction and Java implementation
package com.java2novice.ds.queue;
public class PriorityQueueImpl
{
SuppressWarnings("rawtypes")
private Comparable[]
pQueue;
private int index;
public PriorityQueueImpl(int capacity)
{
pQueue
= new Comparable[capacity];
}
public void insert(Comparable item )
{
if(index
== pQueue.length)
{
System.out.println("The
priority queue is full!! can not insert.");
return;
}
pQueue[index]
= item;
index++;
System.out.println("Adding
element: "+item);
}
SuppressWarnings("unchecked")
public Comparable
remove()
{
if(index
== 0)
{
System.out.println("The
priority queue is empty!! can not remove.");
return
null;
}
int
maxIndex = 0;
for
(int i=1; i
{
if
(pQueue[i].compareTo (pQueue[maxIndex]) > 0)
{
maxIndex
= i;
}
}
Comparable
result = pQueue[maxIndex];
System.out.println("removing:
"+result);
index--;
pQueue[maxIndex]
= pQueue[index];
return
result;
}
public static void
main(String a[])
{
PriorityQueueImpl
pqi = new PriorityQueueImpl(5);
pqi.insert(34);
pqi.insert(23);
pqi.insert(5);
pqi.insert(87);
pqi.insert(32);
pqi.remove();
pqi.remove();
pqi.remove();
pqi.remove();
pqi.remove();
}
}
Average by properties
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main
{
public
static void main(String...args)
{
double
o = Food.menu.stream().collect(Collectors.averagingInt(Food::getCalories));
System.out.println(o);
}
}
enum Type { meat, fish, other }
class Food
{
private
final String name;
private
final boolean vegetarian;
private
final int calories;
private
final Type type;
public
Food(String name, boolean vegetarian, int calories, Type type)
{
this.name = name;
this.vegetarian = vegetarian;
this.calories = calories;
this.type = type;
}
public String getName()
{
return name;
}
public boolean isVegetarian()
{
return vegetarian;
}
public int getCalories()
{
return calories;
}
public Type getType()
{
return type;
}
public
String toString()
{
return name;
}
public
static final List menu =
Arrays.asList( new Food("pork", false, 1800, Type.meat),
new
Food("beef", false, 7100, Type.meat),
new
Food("chicken", false, 1400, Type.meat),
new Food("french
fries", true, 1530, Type.other),
new
Food("rice", true, 3510, Type.other),
new Food("season
fruit", true, 1120, Type.other),
new
Food("pizza", true, 5150, Type.other),
new
Food("prawns", false, 1400, Type.fish),
new Food("salmon", false, 4150,
Type.fish));
}
No comments:
Post a Comment