I have two ArrayLists.
The first contains a group of words with capitalization and
punctuation.
The other contains this same group of words, but with the
capitalization and punctuation removed.
.
ArrayList1 ..... ArrayList2
MURDER! ........ murder
It's ........... its
Hello .......... hello
Yes-Man ........ yesman
ON ............. on
The second array has all the words alphabetized and all the letters in each word alphabetized. It looks something like this:
aemnsy
demrru
ehllo
ist
no
I want to make it so that when I arrange the words in ArrayList two into alphabetical order, all the words from ArrayList one follow suite:
ArrayList1 ..... ArrayList2
Yes-Man ........ aemnsy
MURDER! ........ demrru
Hello .......... ehllo
It's ........... ist
ON ............. no
I tried to make a loop with a for statement or two, but it ended up not working and became very long. How do I do this? How do I do this efficiently?
Here is a function to sort multiple lists based on a single 'key' list. The lists do not need to be the same type, here the key list is type String and it's used to sort a String, Integer, and Double list (Ideone Example):
List<String> key = Arrays.asList("demrru", "ist", "ehllo", "aemnsy", "no");
List<String> list1 = Arrays.asList("MURDER!","It's", "Hello","Yes-Man", "ON");
List<Integer> list2 = Arrays.asList(2, 4, 3, 1, 5); // Also use Integer type
List<Double> list3 = Arrays.asList(0.2, 0.4, 0.3, 0.1, 0.5); // or Double type
// Sort all lists (excluding the key)
keySort(key, list1, list2, list3);
// Sort all lists (including the key)
keySort(key, key, list1, list2, list3);
Output:
// Sorted by key:
[Yes-Man, MURDER!, Hello, It's, ON]
[aemnsy, demrru, ehllo, ist, no]
[1, 2, 3, 4, 5]
[0.1, 0.2, 0.3, 0.4, 0.5]
Sort Function
An Ideone Example can be found here which includes validation of parameters and a test case.
public static <T extends Comparable<T>> void keySort(
final List<T> key, List<?>... lists){
// Create a List of indices
List<Integer> indices = new ArrayList<Integer>();
for(int i = 0; i < key.size(); i++)
indices.add(i);
// Sort the indices list based on the key
Collections.sort(indices, new Comparator<Integer>(){
#Override public int compare(Integer i, Integer j) {
return key.get(i).compareTo(key.get(j));
}
});
// Create a mapping that allows sorting of the List by N swaps.
Map<Integer,Integer> swapMap = new HashMap<Integer, Integer>(indices.size());
// Only swaps can be used b/c we cannot create a new List of type <?>
for(int i = 0; i < indices.size(); i++){
int k = indices.get(i);
while(swapMap.containsKey(k))
k = swapMap.get(k);
swapMap.put(i, k);
}
// for each list, swap elements to sort according to key list
for(Map.Entry<Integer, Integer> e : swapMap.entrySet())
for(List<?> list : lists)
Collections.swap(list, e.getKey(), e.getValue());
}
First Way - I use map whose key is from arrayList2 and value is from arrayList1. Putting data to map is up to you. After sorting arrayList2, I get its value from map.
List<String> arrList1 = new ArrayList<String>();
arrList1.add("MURDER!");
arrList1.add("It's");
arrList1.add("Hello");
arrList1.add("Yes-Man");
arrList1.add("ON");
List<String> arrList2 = new ArrayList<String>();
arrList2.add("demrru");
arrList2.add("aemnsy");
arrList2.add("ist");
arrList2.add("ehllo");
arrList2.add("no");
Map<String, String> map1 = new HashMap<String, String>();
map1.put("aemnsy", "Yes-Man");
map1.put("demrru", "MURDER!");
map1.put("ehllo", "Hello");
map1.put("ist", "It's");
map1.put("no", "ON");
Collections.sort(arrList2);
for (String s : arrList2){
System.out.println(s + "..........." + map1.get(s));
}
Second Way - Another way is you can use only TreeMap which is already sorted instead of two ArrayList.
Map<String, String> map2 = new TreeMap<String, String>();
map2.put("ehllo", "Hello");
map2.put("aemnsy", "Yes-Man");
map2.put("demrru", "MURDER!");
map2.put("no", "ON");
map2.put("ist", "It's");
for (Map.Entry<String, String> entry : map2.entrySet())
{
System.out.println(entry.getKey() + "/" + entry.getValue());
}
Third way - only using 2 ArrayList, but we have to write sorting method by our own. Have you notice that your 2 ArrayList elements such as aemnsy from arrayList2 and Yes-Man from arrayList1 have same index? I use that point.
selectionSort1(arrList2, arrList1);
for(int i = 0; i < arrList1.size(); i++){
System.out.println(arrList2.get(i) + "---" + arrList1.get(i));
}
public static void selectionSort1(List<String> x, List<String> y) {
for (int i=0; i<x.size()-1; i++) {
for (int j=i+1; j<x.size(); j++) {
if (x.get(i).compareTo(x.get(j)) > 0) {
//... Exchange elements in first array
String temp = x.get(i);
x.set(i, x.get(j));
x.set(j, temp);
//... Exchange elements in second array
temp = y.get(i);
y.set(i, y.get(j));
y.set(j, temp);
}
}
}
}
A Quick Answer.
public class MapAlph {
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<String, String>();
String txt = "Murde!r!";
ArrayList<Character> alph = new ArrayList<Character>();
for (int i = 0; i < txt.length(); i++)
if (Character.isLetter(txt.charAt(i)))
alph.add(txt.charAt(i));
Collections.sort(alph);
Collections.reverse(alph);
String val = "";
for (Character c : alph)
val += c;
map.put(txt, val);
System.out.print(txt + " ........ " + map.get(txt));
}
}
You can make use of TreeMap, if you wish.
Map<String, String> sortedMap = new TreeMap<String, String>();
sortedMap.put("demrru", "MURDER!");
sortedMap.put("ist", "It's");
sortedMap.put("aemnsy", "Yes-Man");
sortedMap.put("ehllo", "Hello");
sortedMap.put("no", "ON");
You can try this:
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class SortService {
public static void main(String[] args) {
Map<String, String> originalMap = new HashMap<String, String>();
originalMap.put("aemnsy", "Yes-Man");
originalMap.put("demrru", "MURDER!");
originalMap.put("ehllo", "Hello");
originalMap.put("ist", "It's");
originalMap.put("no", "ON");
Map<String, String> sortedMap = new TreeMap<String, String>(originalMap);
System.out.println(sortedMap);
}
}
output:
{aemnsy=Yes-Man, demrru=MURDER!, ehllo=Hello, ist=It's, no=ON}
Related
Is there a way to put list elements to a String array in java? I sorted a Map by value using a custom Comparator and now trying to put the key(String) elements into an array. The only way I found is looping through the array and the sorted list at the same time and fill up the array that way but it only puts the last element into it.
Example:
My map without sorting: {a=5, b=2, c=8, d=1}
After sorted with custom Comparator: [c=8, a=5, b=2, d=1]
Now I simply need to put the key values (c,a etc.) to the tuple final String[] lettersWithBigValues = new String[n] where n is the length of the tuple.
However, after:
for (int i = 0; i < Integer.parseInt(args[1]); i++) {
System.out.println(lettersWithBigValues[i]+",");
}
The console gives back:
d,d,d,d given that the console line argument is 4
Here is the full function:
public String[] getTopLettersWithValues(final int n){
final String[] lettersWithBigValues = new String[n];
final Map<String, Integer> myMap = new HashMap<>();
int counter = 0;
for (final List<String> record : records) {
if (!myMap.containsKey(record.get(1))) {
myMap.put(record.get(1), counter += Integer.parseInt(record.get(4)));
} else {
myMap.computeIfPresent(record.get(1), (k,v) -> v + Integer.parseInt(record.get(4)));
}
}
System.out.println(myMap);
List<Map.Entry<String, Integer>> sorted = new LinkedList<>(myMap.entrySet());
// Sort list with list.sort(), using a custom Comparator
sorted.sort(valueComparator);
System.out.println(sorted);
for (int i = 0; i < lettersWithBigValues.length; i++) {
for (Map.Entry<String, Integer> values: sorted) {
lettersWithBigValues[i] = values.getKey();
}
}
return lettersWithBigValues;
}
Where records is a List of data read from a csv file.
And here is the comparator:
public Comparator<Map.Entry<String, Integer>> valueComparator = (o1, o2) -> {
Integer v1 = o1.getValue();
Integer v2 = o2.getValue();
return v2.compareTo(v1);
};
You can attain the array of keys as follows:
String [] lettersWithBigValues = myMap.entrySet().stream() // entries of your intial map
.sorted(valueComparator) // sorted by your comparator
.map(Map.Entry::getKey) // mapped to only the key e.g. 'd', 'a'
.toArray(String[]::new); // converted to array
Seems to me that you have mistakenly used a nested for loop, you just need the one:
for (int i = 0; i < lettersWithBigValues.length; i++) {
lettersWithBigValues[i] = sorted.get(i).getKey();
}
That would return the array: c, a, b, d
As an added suggestion you could also have created the Comparator using the Entry.comparingByValue() method.
Comparator<Entry<String,Integer>> valueComparator =
Entry.<String,Integer>comparingByValue().reversed();
It returns a ready made Comparator that compares by the natural order of the value. So to sort in reverse, you just need to tag on the reversed() method which is defined in the Comparator interface.
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}
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.
The problem goes as follows: Jane has friends who she associates a number with. I must output the friends from the least amount of likes to the most likes.
My main curiosity is how can I reverse the order of the map values when outputting.
In my code I had to extract the values through an Iterator (I was unable to use a Collection directly) and then store each String into an ArrayList by inserting each consecutive element at index 0. This, as a result, reversed the order which worked I suppose.
import java.util.*;
import java.io.*;
import static java.lang.System.*;
public class Friends {
public static void main(String args[]) throws IOException
{
Scanner line = new Scanner(new File("friends.dat"));
int trials = line.nextInt();
for(int k = 0 ; k < trials ; k++)
{
TreeMap<Integer, String> m = new TreeMap<Integer,String>();
int subtrials = line.nextInt();
for(int a = 0; a < subtrials ; a++)
{
String name = line.next();
int likes = line.nextInt();
m.put(likes,name);
}
Iterator iter = m.values().iterator(); //**Code of interest starts here**
ArrayList<String> list = new ArrayList<String>();
while(iter.hasNext()) {
list.add(0, (String)iter.next());
}
for(int a = 0 ; a < list.size() ; a++)
{
if(a == list.size() - 1)
out.print(list.get(a));
else
out.print(list.get(a) + ", ");
}
out.println();
}
}
}
You can use a custom comparator to reverse the order of entries in the map (note that this only applies to TreeMap - other map implementations don't care about ordering).
public static void main(String[] args) {
TreeMap<Integer, String> map = new TreeMap<>((key1, key2) -> Integer.compare(key2, key1)); //Custom comparator.
map.put(1, "Bob");
map.put(3, "Baz");
map.put(2, "Foo");
System.out.println(map);
}
Using the number of likes as a key seems strange, as multiple friends might have the same number of likes.
In Java 8, I'd do the following:
Map<String, Integer> map = new HashMap<>();
map.put("Jack", 7);
map.put("Jill", 3);
map.put("John", 12);
map.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue((a, b) -> b.compareTo(a)))
.forEach(System.out::println);
Essentially, this turns the map entries into a stream, compares them by value using a comparator that reverses the natural order, and then prints out every entry.
Which results in:
John=12
Jack=7
Jill=3
Please try this:
m.forEach((a,b)->System.out.print(b+", "));
This will give you a sorted map, from the least amount of likes to the most likes.
If you want a sorted map from the most likes to the least amount of likes, you can do this:
TreeMap<Integer, String> m = new TreeMap<Integer,String>(Collections.reverseOrder());
You could simply reverse your list.
list.reverse();
Alternately, you could use the TreeMap constructor with a reverse comparator, to store the map in descending order.
... = new TreeMap<>(Collections.reverseOrder(Integer::compare));
I'm trying to loop thu a map using the codes:
Map<String, List<String>> newMap = new HashMap<String, List<String>>();
List<String> newList = new ArrayList<String>();
Assign some default values on the Map
for ( int m = 1; m < attribteList.size(); m = m+2) {
String newName = newList.get(m);
newMap.put(newName , newList);
}
know I need to add values in the Map
for (another loop) {
String value1 = anyvalue;
String value2 = anyvalue;
Iterator it = pmMap.entrySet().iterator();
int cnt = 1;
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
if(value1.equalsIgnoreCase(pairs.getKey().toString())) {
for (List<String> list : pmMap.values()) {
int a = list.indexOf(list);
if (a == cnt) {
list.add(value2);
}
}
}
cnt++;
}
Problem is my loop doesn't work. I need to add value2 from the Map based from there position or value from the map
Like:
If Map String (15) is equal to value1 (15)
Find the Map Liststring with the value of 15 and place value2 inside.
Output data should be like this:
MAP: 15=[value2, 0, 0, 0] 16=[value2, 0, 0, 0, 0] 17=[value2, 0, ,0 ,0]
Anyone knows how to loop or search for the position or correct list?
First, I am guessing that this List<String> newList = new ArrayList<String>(); should be inside the loop you are updating your HashMap otherwise as #tobias_k mentioned you are inserting the same value to every key. I guess you don't want that.
You can use keySet() to get the key of your Map and loop in it:
Set<String> set = pmMap.keySet();
for(String key : set) {
ArrayList<String> list = null;
if(value1.equals(key)) {
list = pmMap.get(key);
list.add(value2);
pmMap.put(key, list);
}
I haven't checked the code but you got the idea.
Since you are assigning the same list to all values in the map you need not loop through the entry set. You could just get the value and do a replace all like Collections.replaceAll(list, value1, value2);
List<String> list = pmMap.get(value1);
if(list != null){
Collections.replaceAll(list, value1, value2);
}
A sample
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Test {
public static void main(String[] args) {
Map<String, List<String>> pmMap = new HashMap<String, List<String>>();
List<String> newList = new ArrayList<String>(){{ add("15"); add("16"); add("17"); add("18");}};
for (int m = 0; m < newList.size(); m++) {
String newName = newList.get(m);
pmMap.put(newName , newList);
}
System.out.println(pmMap);
String value1 = "15";
String value2 = "19";
List<String> list = pmMap.get(value1);
if(list != null){
Collections.replaceAll(list, value1, value2);
}
System.out.println(pmMap);
}
}