Using LinkedList with sort method - java

I am currently trying to use a LinkedList to print a list of keys from their highest number of occurences to lowest. I am trying to use the sort method on the getValue method of the entry but it is not working. Any ideas what I'm doing wrong. Here is a snippet of my code
// Beginning tree map
Map<String, Integer> map1 = new TreeMap<>();
String[] words1 = text.split("[ \n\t\r.,;:!?(){ ]");
for (int i = 0; i < words1.length; i++)
{
String key = words1[i].toLowerCase();
if (key.length() > 0)
{
if (!map1.containsKey(key))
{
map1.put(key, 1);
}
else
{
int value = map1.get(key);
value++;
map1.put(key, value);
}
}
}
Set<Map.Entry<String, Integer>> entrySet1 = map1.entrySet();
// Get key and value from each entry
System.out.println("Treemap: " + map1);
for (Map.Entry<String, Integer> entry: entrySet1)
System.out.println(entry.getValue() + "\t" + entry.getKey());
System.out.println("");
// Beginning for LinkedList
LinkedList<Entry<String, Integer>> linkedList = new LinkedList<>(entrySet1);
System.out.println("linkedList:");
System.out.println(linkedList);
System.out.println(linkedList.sort(entrySet1.getKey());
With my current output
Treemap: {a=2, class=1, fun=1, good=3, have=3, morning=1, visit=1}
2 a
1 class
1 fun
3 good
3 have
1 morning
1 visit
linkedList:
[a=2, class=1, fun=1, good=3, have=3, morning=1, visit=1]
So my ultimate question is, how can i pass my getValue method to the LinkedList in order to print them in a sorted order.

Related

How do I print a specific number of items in a treemap

I'm trying to print out only 10 values in this treemap, which I filled in from a hashmap.But all the ways I see to traverse the list only allows me to print out all the keys and values and not just 10.
TreeMap<Integer, String> displayTen = new TreeMap<Integer, String>();
displayTen.putAll(allValues);
for (Map.Entry m : displayTen.entrySet()) {
System.out.println(m.getKey() + " " + m.getValue());
}
int count = 0;
TreeMap<K,V> resultMap = new TreeMap<K,V>();
for (Map.Entry<K,V> entry:source.entrySet()) {
if (count == 10)
break;
resultMap.put(entry.getKey(), entry.getValue());
count++;
}
return resultMap;

Java ArrayList sort two lists in same order

I have two ArrayLists in Java. Both lists are unsorted.
ArrayList<Integer> listOne = new ArrayList<>();
listOne.add(2);
listOne.add(1);
listOne.add(4);
listOne.add(8);
listOne.add(6);
ArrayList<String> listTwo = new ArrayList<>();
listTwo.add("ant");
listTwo.add("bear");
listTwo.add("cat");
listTwo.add("dog");
listTwo.add("zebra");
I want to sort listOne in natural order and each item of listTwo should be sorted according to the position in listOne:
What I have so far is:
Collections.sort(listOne);
for (int i = 0; i < listOne.size(); i++) {
int intTest = listOne.get(i);
String stringTest = listTwo.get(i);
System.out.println(intTest);
System.out.println(stringTest);
}
This prints :
1 ant, 2 bear, 4 cat , 6 dog , 8 zebra
My expected print output is:
1 bear, 2 ant, 4 cat, 6 zebra, 8 dog
So that when the item of listOne "1", that changed the position from 2nd to 1st, the item "bear" in listTwo, that was on the 2nd position, should also print on the 1st position.
What would be the most simple and efficient way to do this?
Create an ordered list of indices:
int n = listOne.size();
assert n == listTwo.size();
Integer[] indices = new Integer[n];
for (int i = 0; i < n; ++i) {
indices[i] = i;
}
Sort that list using a comparator that compares indices by looking at the corresponding elements in listOne.
Arrays.sort(
indices,
new Comparator<Integer>() {
public int compare(Integer a, Integer b) {
return listOne.get(a).compareTo(listOne.get(b));
}
});
Now you can use indices to reorder both lists:
static <T> void reorder(Integer[] indices, List<T> mutatedInPlace) {
List<T> tempSpace = new ArrayList<T>(indices.length);
for (int index : indices) {
tempSpace.add(mutatedInPlace.get(index);
}
mutatedInPlace.clear();
mutatedInPlace.addAll(tempSpace);
}
reorder(indices, listOne);
reorder(indices, listTwo);
TreeMap best suits this situation. It inserts the data in sorted order so basically store the key and against each key you can store the animal.
Map<Integer,String> sortedMap = new TreeMap<Integer,String>();
sortedMap.push(listOne.get(i),listTwo.get(listOne.get(i)));
In case you want to stick to ArrayList, you can iterate over the listOne and push it in HashMap<Integer,String>
iterate over list (for example i)
map.put( listOne.get(i), secondList.get(i));
So the hashMap would be like (2, "ant");
Collections.sort(listOne);
Against each entry, you can get the corresponding animal from map
We can use HashMap data structure, It contains “key-value” pairs and allows retrieving the value by key.
int i = 0;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Here we’re storing the items from listOne as keys and their position as a value in the HashMap.
for (Integer num : listOne) {
map.put(num, i);
i++;
}
We’re printing the elements from listTwo as per the items from the listOne changed their position.
Collections.sort(listOne);
for (Integer num : listOne) {
System.out.println(num + " " + listTwo.get(map.get(num)));
}
One Solution:
int i = 0;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Integer num : listOne) {
map.put(num, i);
i++;
}
Collections.sort(listOne);
for (Integer num : listOne) {
System.out.println(num + " " + listTwo.get(map.get(num)));
}
Output is:
1 bear,
2 ant,
4 cat,
6 zebra,
8 dog
If you use a Map<Integer, String> for this, you don't even need to sort it if you take the TreeMap implementation.
It basically works as follows:
public class StackoverflowMain {
public static void main(String[] args) {
// initialize a map that takes numbers and relates Strings to the numbers
Map<Integer, String> animals = new TreeMap<Integer, String>();
// enter ("put" into the map) the values of your choice
animals.put(2, "ant");
animals.put(1, "bear");
animals.put(4, "cat");
animals.put(8, "dog");
animals.put(6, "zebra");
// print the whole map using a Java 8 forEach statement
animals.forEach((index, name) -> System.out.println(index + ": " + name));
}
}
This code will output
1: bear
2: ant
4: cat
6: zebra
8: dog
Putting the suggestions of all the friendly and helpful people together (plus some other research and test), here is the final code I came up with:
ArrayList<String> listOne = new ArrayList<>();
listOne.add("one");
listOne.add("eight");
listOne.add("three");
listOne.add("four");
listOne.add("two");
ArrayList<String> listTwo = new ArrayList<>();
listTwo.add("ant");
listTwo.add("bear");
listTwo.add("cat");
listTwo.add("dog");
listTwo.add("zebra");
Map<String, String> sortedMap = new TreeMap<String, String>();
for (int i = 0; i < listOne.size(); i++) {
String stringkey = listOne.get(i);
String stringValue = listTwo.get(i);
sortedMap.put(stringkey, stringValue);
}
print output = {eight=bear, four=dog, one=ant, three=cat, two=zebra}

How to compare a HashMap and Arraylist to find similar values

I'm using this algorithm to compare two sets of values: a HashMap<Integer,ArrayList<Integer>> and the other ArrayList<Integer>. The goal of the program is to compare each value in the HashMap, with the values in the ArrayList, and returns a new HashMap of the similar values. So far, my program runs normally, but it returns false results.
ArrayList Example
[1.0.1.0.0]
HashMap Example
[1.0.1.1.0]
[0.1.1.0.0]
[0.1.1.1.0]
Result:
4
3
2
My Program
int k = 1;
List<Integer> listOperateur = new ArrayList<Integer>();
HashMap<Integer, Integer> sim = new HashMap<Integer, Integer>();
for (Map.Entry<Integer, ArrayList<Integer>> e : hmm.entrySet()) {
count = 0;
for (Integer mapValue : e.getValue()) {
if (mapValue.equals(listOperateur.get(k))) {
count++;
}
}
sim.put(e.getKey(), count);
k++;
}
System.out.println("HASHMAP RESULT:");
LinkedHashMap<Integer, ArrayList<Integer>> hmm = new LinkedHashMap<>();
for (Entry<Integer, List<String>> ee : hm.entrySet()) {
Integer key = ee.getKey();
List<String> values = ee.getValue();
List<Integer> list5 = new ArrayList<>();
for (String temp : global) {
list5.add(values.contains(temp) ? 1 : 0);
}
hmm.put(key, (ArrayList<Integer>) list5);
}
//nouvelle list operateur
List<Integer> list6 = new ArrayList<Integer>();
System.out.println("liste operateur");
List<Integer> listOperateur = new ArrayList<Integer>();
listOperateur.add(1);
listOperateur.add(0);
listOperateur.add(0);
listOperateur.add(0);
Iterator iter = listOperateur.iterator();
while (iter.hasNext()) {
System.out.println(iter.next());
}
//calcule similarité
System.out.println("HASHMAP SIMILIRATE RESULT:");
HashMap<Integer, Integer> sim = new HashMap<Integer, Integer>();
int count;
int k = 0;
for (Map.Entry<Integer, ArrayList<Integer>> e : hmm.entrySet()) {
//if (e.getValue() != null) {
count = 0;
//you can move this part to another method to avoid deep nested code
for (Integer mapValue : e.getValue()) {
if (mapValue.equals(listOperateur.get(k))) {
count++;
}
}
sim.put(e.getKey(), count);
k++;
}
I believe you're attempting to rely on the insertion order of objects into the HashMap which is not wise, as order is not preserved. Instead, try changing hmm's type from HashMap to LinkedHashMap and see if that solves your problem.
Edit: Also, you should probably initialize k to 0 instead of 1.

Is there a way to infinitely loop through Map elements in java?

Suppose I have a Map with m elements in it, like the following.
Map<String,Integer> mp = new HashMap<String,Integer>();
mp.put("Delhi",1);
mp.put("Bombay",1);
mp.put("Bangalore",1);
Here, m = 3. I would like to access the map of above elements in a cyclic order for specific number of times n, where n != m. Each time I access the Map I want to get the "next" element in the Map (so that implies that the Map entries are somehow ordered). If I get to the end of the Map I want to start over again at the beginning, since I want in all cases to access the map exactly n times. There is no relationship between n and m. Each time I access a map element I want to increase the value of that element by 1.
For example, given the above Map with 3 elements (m == 3), and supposing I want to access the Map five times in total (n == 5). The following should happen:
step-->String(Key)-->Integer(Value)
1-->Delhi-->2
2-->Bombay-->2
3-->Bangalore-->2
4-->Delhi-->3
5-->Bombay-->3
Any suggestions on this would be appreciated, even change of DataStructure as well.
I am specifically looking to loop through the map elements in tandem with an external loop.
What I don't want: suppose I have a for loop say
for(1 to numberofcycles)
{
for(iterate-->mapelements)
{
//looping mapelements
}
}
I would be looping through the map numberofcycles * numberofmap elements which is not what i am expecting to achieve.
Instead, I would like to achieve to loop through mapelements for exactly numberofcycles in cyclic order and changing/adding 1 to value after each visit.
i.e.
keep iterating through map in cyclic order until specific condition is reached.
As I understand it, you want to make a total of n trips, each one to a different destination, and you're visiting those destinations in a predefined order. How about something like this...
If you want to specify the order independent of the Map
Map<String,Integer> mp = new HashMap<>();
mp.put("Delhi",1);
mp.put("Bombay",1);
mp.put("Bangalore",1);
int numberOfTrips = 5;
List<String> orderOfVisits = Arrays.asList("Delhi", "Bombay", "Bangalore");
Iterator<String> visiterator = orderOfVisits.iterator();
for (int i = 0; i < numberOfTrips; i++) {
// Get a new iterator if we've exhausted the previous one
if (!visiterator.hasNext()) {
visiterator = orderOfVisits.iterator();
}
// Get the correct city and increment the counter
String key = visiterator.next();
mp.put(key, mp.get(key) + 1);
}
// demonstrate that the map contains the correct values
for (Entry<String, Integer> entry: mp.entrySet()) {
System.out.println("Key:" + entry.getKey() + ", Value:" + entry.getValue());
}
If you want the Map to govern the order
To visit the cities in the order in which they were added to the Map, you can do the following:
1) Change the declaration of mp from HashMap to LinkedHashMap:
Map<String,Integer> mp = new LinkedHashMap<>();
2) Iterate over the keyset of the Map:
visiterator = mp.keySet().iterator();
If you want to specify the order with a Comparator
1) Change the declaration of mp to TreeMap, supplying a Comparator:
Map<String,Integer> map = new TreeMap<>(Comparator.naturalOrder());
2) Iterate over the keyset of the Map as in the above example.
All the code
public static void tripsInConfigurableOrder() {
Map<String, Integer> mp = new HashMap<String, Integer>();
mp.put("Delhi", 1);
mp.put("Bombay", 1);
mp.put("Bangalore", 1);
int numberOfTrips = 5;
List<String> orderOfVisits = Arrays.asList("Delhi", "Bombay", "Bangalore");
Iterator<String> visiterator = orderOfVisits.iterator();
for (int i = 0; i < numberOfTrips; i++) {
if (!visiterator.hasNext()) {
visiterator = orderOfVisits.iterator();
}
String key = visiterator.next();
mp.put(key, mp.get(key) + 1);
}
for (Entry<String, Integer> entry : mp.entrySet()) {
System.out.println("Key:" + entry.getKey() + ", Value:" + entry.getValue());
}
}
public static void tripsInNaturalOrder() {
Map<String, Integer> mp = new LinkedHashMap<>();
mp.put("Delhi", 1);
mp.put("Bombay", 1);
mp.put("Bangalore", 1);
int numberOfTrips = 5;
Iterator<String> visiterator = mp.keySet().iterator();
for (int i = 0; i < numberOfTrips; i++) {
if (!visiterator.hasNext()) {
visiterator = mp.keySet().iterator();
}
String key = visiterator.next();
mp.put(key, mp.get(key) + 1);
}
for (Entry<String, Integer> entry : mp.entrySet()) {
System.out.println("Key:" + entry.getKey() + ", Value:" + entry.getValue());
}
}
public static void usingComparator() {
Map<String, Integer> mp = new TreeMap<>(Comparator.naturalOrder());
mp.put("Delhi", 1);
mp.put("Bombay", 1);
mp.put("Bangalore", 1);
int numberOfTrips = 5;
Iterator<String> visiterator = mp.keySet().iterator();
for (int i = 0; i < numberOfTrips; i++) {
if (!visiterator.hasNext()) {
visiterator = mp.keySet().iterator();
}
String key = visiterator.next();
mp.put(key, mp.get(key) + 1);
}
for (Entry<String, Integer> entry : mp.entrySet()) {
System.out.println("Key:" + entry.getKey() + ", Value:" + entry.getValue());
}
}
public static void main(String[] args) {
tripsInConfigurableOrder();
tripsInNaturalOrder();
usingComparator();
}
Map<String,Integer> mp = new HashMap<String,Integer>();
mp.put("Delhi",1);
mp.put("Bombay",1);
mp.put("Bangalore",1);
for (int i = 0 ; i < numberOfCycles; i++){
for (String key : mp.keySet()){
mp.put(key,mp.get(key)+1);
}
}
How about using the while loop and put iteration inside a while loop like this?
Map<String, Integer> map = ...
while (true or some condition)
{
for (Map.Entry<String, Integer> entry : map.entrySet())
{
map.put(key, map.get(key) + 1);
}
if (some condition met)
some condition = false
}
EDIT
I read your edited post and here is a solution to what you want to do.
You could use break to get out of the for loop when you reached maxCycle.
Map<String, Integer> map = ...
int numberOfCycles = 0;
int maxCycle = 10;
while (numberOfCycles < maxCycle)
{
for (Map.Entry<String, Integer> entry : map.entrySet())
{
if (++numberOfCycles < maxCycle)
map.put(key, map.get(key) + 1);
else
break;
}
}
Say you start from 0 and maxCycle is 5. If you have iterated 5 times, it will go to else and call break. After break you will go back to while loop and the exit condition is satisfied.

Reverse Map.key, map.value output

I have this output and it comes out in the opposite order. The last printout is what i want to be the first print out. How can I reverse it? It is a HashMap.
System.out.println();
int c = 0;
System.out.print(newName + "= ");
for (Map.Entry<Integer, Integer> entry : result.entrySet()) {
System.out.print(entry.getValue() + "X^" + entry.getKey());
c++;
if (c != result.size()) {
System.out.print("+");
}
To preserve insertion order when iterating use a LinkedHashMap instead of a HashMap, and to go in reverse do this:
List<Map.Entry<Integer, Integer>> entries = new ArrayList<>(result.entrySet());
Collections.reverse(entries);
for (Map.Entry<Integer, Integer> entry : entries) {
// same body as before
}
Alternatively, we can use a reverse iterator:
List<Map.Entry<Integer, Integer>> entries = new ArrayList<>(result.entrySet());
ListIterator<Map.Entry<Integer, Integer>> iter = entries.listIterator();
while (iter.hasPrevious()) {
Map.Entry<Integer, Integer> entry = iter.previous();
// same body as before
}

Categories

Resources